How to test async exception? - flutter-test

I would like to figure out how to test that a widget throws an async exception.
Exception, that is created on the widget's initState:
Future<void> _asyncError() async =>
Future.delayed(Duration(microseconds: 1), () => throw FaultRoots.async);
The test, that does not detect the exception and then throws it:
try {
await tester.pumpWidget(widget);
await tester.pumpAndSettle();
expect(tester.takeException(), isNotNull);
expect(tester.takeException().toString(), contains(p.route));
} catch (ex) {
print(ex.toString());
}
Exception:
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following message was thrown running a test:
/fault/async
When the exception was thrown, this was the stack:
#0 _FaultPageState._asyncError.<anonymous closure> (package:flutter_firebase_hello/pages/fault_page.dart:26:55)
#8 FakeTimer._fire (package:fake_async/fake_async.dart:316:16)
#9 FakeAsync._fireTimersWhile (package:fake_async/fake_async.dart:240:13)
#10 FakeAsync.elapse (package:fake_async/fake_async.dart:137:5)
#11 AutomatedTestWidgetsFlutterBinding.pump.<anonymous closure> (package:flutter_test/src/binding.dart:965:28)
#14 TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:72:41)
#15 AutomatedTestWidgetsFlutterBinding.pump (package:flutter_test/src/binding.dart:961:27)
#16 WidgetTester.pumpAndSettle.<anonymous closure> (package:flutter_test/src/widget_tester.dart:640:23)
<asynchronous suspension>
<asynchronous suspension>
(elided 10 frames from dart:async and package:stack_trace)

Async exceptions can be caught by runZonedGuarded:
await runZonedGuarded(() async {
await tester.pumpWidget(makeTestable(widget));
await tester.pumpAndSettle();
}, (error, stack) {
... error validation ...
});

Related

No implementation found for method getAll on channel dev.fluttercommunity.plus/package_info

I'm trying to debug a project for windows, and I'm having this problem:
It runs and stops at Parse().initialize giving the error
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel dev.fluttercommunity.plus/package_info)
#0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:175:7)
<asynchronous suspension>
#1 MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:377:43)
<asynchronous suspension>
#2 MethodChannelPackageInfo.getAll (package:package_info_plus_platform_interface/method_channel_package_info.dart:13:17)
<asynchronous suspension>
#3 PackageInfo.fromPlatform (package:package_info_plus/package_info_plus.dart:36:26)
<asynchronous suspension>
#4 Parse.initialize (package:parse_server_sdk_flutter/parse_server_sdk.dart:67:39)
<asynchronous suspension>
#5 initializeParse (package:spa/main.dart:73:3)
<asynchronous suspension>
#6 main`enter code here` (package:spa/main.dart:27:3)
<asynchronous suspension>
I've tried everything, clean and pub get. When it runs for the web it works normally, it just gives an error when I go to run for windows
I managed to solve the problem.
To solve the problem I had to add the package_info_plus_windows plugin
flutter pub add package_info_plus_windows
Then in the Parse method I added this
import 'package:package_info_plus_platform_interface/package_info_data.dart';
Future<void> initializeParse() async {
const appId = 'xxxx';
const clientKey = 'xxxxx';
const serverURL = 'xxxx';
const liveQueryUrl = 'xxxx';
PackageInfoData packageInfoWindows = await PackageInfoWindows().getAll();
await Parse().initialize(
appId,
serverURL,
clientKey: clientKey,
liveQueryUrl: liveQueryUrl,
autoSendSessionId: true,
debug: true,
appName: packageInfoWindows.appName,
appVersion: packageInfoWindows.version,
appPackageName: packageInfoWindows.packageName,
);
}
In my case PackageInfoData was not accessible so my solution was:
var packageInfoWindows = await PackageInfoWindows().getAll();
await Parse().initialize(
keyApplicationId,
keyParseServerUrl,
clientKey: keyClientKey,
autoSendSessionId: true,
debug: true,
appName: packageInfoWindows.appName,
appVersion: packageInfoWindows.version,
appPackageName: packageInfoWindows.packageName
);

Cannot subscribe to a private or presence channel because no Authorizer has been set. Call PusherOptions.setAuthorizer() before connecting to Pusher

In a chat application,
Laravel 7.x,
Vuejs 2,
Flutter 2.8 and Pusher
Pacakges I use pusherjs, Laravel echo, pusher-php-server and Flutter pusher_client.
in Laravel & Vue public and private channels work fine, in with Flutter public channel also working but, subscribing to private channel show the following error.
Cannot subscribe to a private or presence channel because no Authorizer has been set. Call PusherOptions.setAuthorizer() before connecting to Pusher
W/System.err(10758): java.lang.IllegalStateException: Cannot subscribe to a private or presence channel because no Authorizer has been set. Call PusherOptions.setAuthorizer() before connecting to Pusher
W/System.err(10758): at com.pusher.client.Pusher.throwExceptionIfNoAuthorizerHasBeenSet(Pusher.java:376)
W/System.err(10758): at com.pusher.client.Pusher.subscribePrivate(Pusher.java:281)
W/System.err(10758): at com.github.chinloyal.pusher_client.pusher.PusherService.subscribe(PusherService.kt:152)
W/System.err(10758): at com.github.chinloyal.pusher_client.pusher.PusherService.access$subscribe(PusherService.kt:30)
W/System.err(10758): at com.github.chinloyal.pusher_client.pusher.PusherService$register$1.onMethodCall(PusherService.kt:56)
W/System.err(10758): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
W/System.err(10758): at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:178)
W/System.err(10758): at io.flutter.embedding.engine.dart.DartMessenger.lambda$handleMessageFromDart$0$DartMessenger(DartMessenger.java:206)
W/System.err(10758): at io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$R4HPk6oFVb-i-YR_PN9YE6kqx1I.run(Unknown Source:12)
W/System.err(10758): at android.os.Handler.handleCallback(Handler.java:883)
W/System.err(10758): at android.os.Handler.dispatchMessage(Handler.java:100)
W/System.err(10758): at android.os.Looper.loop(Looper.java:237)
W/System.err(10758): at android.app.ActivityThread.main(ActivityThread.java:7948)
W/System.err(10758): at java.lang.reflect.Method.invoke(Native Method)
W/System.err(10758): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
W/System.err(10758): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
D/PusherClientPlugin(10758): Event stream cancelled.
D/PusherClientPlugin(10758): Event stream listening...
D/PusherClientPlugin(10758): [BIND] chat-event
E/flutter (10758): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(SUBSCRIBE_ERROR, Cannot subscribe to a private or presence
channel because no Authorizer has been set. Call PusherOptions.setAuthorizer() before connecting to Pusher, java.lang.IllegalStateException: Cannot subscribe to a private or presence channel because no Authorizer has been set. Call PusherOptions.setAuthorizer() before connecting to Pusher
E/flutter (10758): at com.pusher.client.Pusher.throwExceptionIfNoAuthorizerHasBeenSet(Pusher.java:376)
E/flutter (10758): at com.pusher.client.Pusher.subscribePrivate(Pusher.java:281)
E/flutter (10758): at com.github.chinloyal.pusher_client.pusher.PusherService.subscribe(PusherService.kt:152)
E/flutter (10758): at com.github.chinloyal.pusher_client.pusher.PusherService.access$subscribe(PusherService.kt:30)
E/flutter (10758): at com.github.chinloyal.pusher_client.pusher.PusherService$register$1.onMethodCall(PusherService.kt:56)
E/flutter (10758): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
E/flutter (10758): at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:178)
E/flutter (10758): at io.flutter.embedding.engine.dart.DartMessenger.lambda$handleMessageFromDart$0$DartMessenger(DartMessenger.java:206)
E/flutter (10758): at io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$R4HPk6oFVb-i-YR_PN9YE6kqx1I.run(Unknown Source:12)
E/flutter (10758): at android.os.Handler.handleCallback(Handler.java:883)
E/flutter (10758): at android.os.Handler.dispatchMessage(Handler.java:100)
E/flutter (10758): at android.os.Looper.loop(Looper.java:237)
E/flutter (10758): at android.app.ActivityThread.main(ActivityThread.java:7948)
E/flutter (10758): at java.lang.reflect.Method.invoke(Native Method)
E/flutter (10758): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/flutter (10758): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
E/flutter (10758): , null)
E/flutter (10758): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter (10758): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167:18)
E/flutter (10758): <asynchronous suspension>
this is the function inside controller
public function newMessage(Request $request, $roomId)
{
$newMessage = new Message();
$newMessage->user_id = Auth::id();
$newMessage->room_id = $roomId;
$newMessage->message = $request->message;
$newMessage->save();
broadcast(new NewChatMessage($newMessage))->toOthers();
return response()->json($newMessage);
}
this is the event class
class NewChatMessage implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct(Message $message)
{
$this->message = $message;
}
public function broadcastOn()
{
return new PrivateChannel('chat.'. $this->message->room_id);
}
public function broadcastAs()
{
return 'chat-event';
}
}
channels.php
Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
if(Auth::check()){
return ['id'=> $user->id, 'name'=> $user->name ];
}
});
In Flutter I use flutter_client package the following code is copied from it's documentation
Future<void> _initPusher() async {
String token = await _store.read('token');
try {
pusher = PusherClient(
"6f8...c3",
PusherOptions(
host: '10.10.10.251',
encrypted: false,
auth: PusherAuth(
'http://10.10.10.251:8000/broadcasting/auth',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token'
},
),
cluster: 'eu',
),
enableLogging: true,
);
channel = pusher.subscribe("private-chat.2");
pusher.onConnectionStateChange((state) {
print(
"previousState: ${state.previousState}, currentState: ${state.currentState}");
});
pusher.onConnectionError((error) {
print("error: ${error.message}");
});
channel.bind('chat-event', (event) {
print(event.data);
});
} catch (e) {
print(e);
}
}
I can successfully subscribe to public channel by bellow code.
Future<void> _initPusher() async {
try {
pusher = PusherClient(
"6f8...c3",
PusherOptions(
encrypted: false,
cluster: 'eu',
),
enableLogging: true,
);
channel = pusher.subscribe("public-channel-name");
pusher.onConnectionStateChange((state) {
print(
"previousState: ${state.previousState}, currentState: ${state.currentState}");
});
pusher.onConnectionError((error) {
print("error: ${error.message}");
});
channel.bind('chat-event', (event) {
print(event.data);
});
} catch (e) {
print(e);
}
}
your help is really appreciated.
Give this a shot.
Android Pusher AuthorizationFailureException: FileNotFoundException
removing the
'Content-Type': 'application/json',
From your headers might do the trick.
#usman fawwaz, I solved using pusher_client in Flutter. If you want to subscribe to a private channel init pusher as follow.
Future<void> _initPusher() async {
String token = await Store.read('token');
try {
pusher = PusherClient(
pusherKey,
PusherOptions(
host: basePath,
encrypted: false,
auth: PusherAuth(
basePath + "/broadcasting/auth",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token'
},
),
cluster: 'eu',
),
enableLogging: true,
);
channel = pusher?.subscribe("private-chat." + widget.room.id.toString());
pusher?.onConnectionStateChange((state) {
print(
"previousState: ${state?.previousState}, currentState: ${state?.currentState}");
});
pusher?.onConnectionError((error) {
print("error: ${error?.message}");
});
channel?.bind('chat-event', (event) {
setState(() {});
});
} catch (e) {
print(e.toString());
}
}
for me the key point was; laravel by default has a route named "broadcasting/auth" I didn't know this.
Pusher itself made a package called pusher_channels_flutter: ^2.0.2 I want to switch to this package, here also I have subscription problem with private package.

Laravel 5 uploading zip file showing Undefined variable: e

I've created a file upload method and the file uploading with the file extension like jpg, png etc are successful. However, when I upload a zip file, it says me "Undefined variable: e". To find, I did dd() at the beginning of the respective method but it still says the above error. My route is as below:
Route::post('media/savedata/{id?}/{page?}', 'Administrator\MedialibraryController#savedata');
The method is as below:
public function savedata($id, $page, Request $request) {
...
}
The content of the "network" tab is as below:
Request URL: http://localhost/stmd/administrator/media/savedata/0/1
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade
------WebKitFormBoundaryaHtERzAAThbQB4ae
Content-Disposition: form-data; name="_token"
TXLvBGRXrdjpQbhAjm18MTxkiHamauvcjhKBhl6n
------WebKitFormBoundaryaHtERzAAThbQB4ae
Content-Disposition: form-data; name="fileType"
I
------WebKitFormBoundaryaHtERzAAThbQB4ae
Content-Disposition: form-data; name="fileName"; filename="gradle-3.5-bin.zip"
Content-Type: application/zip
My intention is: If zip file is upload then it will redirect to another page however, I can't do this because even dd() is not working.
UPDATE:
Below is the Laravel Log:
[2018-07-23 11:59:51] local.ERROR: Undefined variable: e {"exception":"[object] (ErrorException(code: 0): Undefined variable: e at /var/www/html/stmd/app/Exceptions/Handler.php:76)
[stacktrace]
#0 /var/www/html/stmd/app/Exceptions/Handler.php(76): Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(8, 'Undefined varia...', '/var/www/html/s...', 76, Array)
#1 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(83): App\\Exceptions\\Handler->render(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Exceptions\\PostTooLargeException))
#2 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(55): Illuminate\\Routing\\Pipeline->handleException(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Exceptions\\PostTooLargeException))
#3 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(46): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#4 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#5 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#6 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#7 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(151): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#8 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(116): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))
#9 /var/www/html/stmd/public/index.php(58): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#10 /var/www/html/stmd/index.php(4): include('/var/www/html/s...')
#11 {main}
"}
My Handler.php content is below:
public function render($request, Exception $exception)
{
if($this->isHttpException($exception)){
$logFile = 'laravel.log';
Log::useDailyFiles(storage_path().'/logs/'.$logFile);
//echo Route::getCurrentRoute()->getAction();
//echo $exception->getStatusCode();exit;
switch ($exception->getStatusCode()) {
case 404:
Log::info('Unable to find page.');
return response()->view('errors.404',[],404);
break;
case 500:
Log::error('In Server is really going wrong.');
return response()->view('errors.500',[],500);
break;
default:
return $this->renderHttpException($e);
break;
}
}
return parent::render($request, $exception);
}
}
Change
return $this->renderHttpException($e);
to
return $this->renderHttpException($exception);
in
app/Exceptions/Handler.php
You can handle the FileException exception inside your exception handler at app/Exceptions/Handler.php. Update the render method to add in the code you need. For example, if you'd like to return a validation exception, you will need to handle the validation inside the exception handler for the FileException exception.
public function render($request, Exception $exception)
{
if ($exception instanceof \Symfony\Component\HttpFoundation\File\Exception\FileException) {
// create a validator and validate to throw a new ValidationException
return Validator::make($request->all(), [
'your_file_input' => 'required|file|size:5000',
])->validate();
}
return parent::render($request, $exception);
}
This is untested, but should give you the general idea.
if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException)
return \Redirect::to('administrator/media')->with('errorMessage', 'Please upload an image.');

How can I set up a letsencrypt SSL certificate and use it in a https server in dart?

I try:
import 'dart:io';
import "dart:isolate";
main() {
SecurityContext context = new SecurityContext();
var chain = Platform.script.resolve('/etc/letsencrypt/live/example.com/chain.pem').toFilePath();
var key = Platform.script.resolve('/etc/letsencrypt/live/example.com/privkey.pem').toFilePath();
context.useCertificateChain(chain);
// context.usePrivateKey(key, password: '?????');
context.usePrivateKey(key);
HttpServer.bindSecure(InternetAddress.ANY_IP_V4, 443, context).then((server) {
server.listen((HttpRequest request) {
request.response.write('Hello, world!');
request.response.close();
});
});
}
But not work! Any ideas to make this work?
https://api.dartlang.org/stable/1.24.2/dart-io/HttpServer-class.html#id_bindSecure
Error Message:
Unhandled exception:
TlsException: Failure in usePrivateKeyBytes (OS Error:
KEY_VALUES_MISMATCH(x509_cmp.c:331), errno = 0)
#0 _SecurityContext.usePrivateKeyBytes (dart:io-patch/secure_socket_patch.dart:156)
#1 _SecurityContext.usePrivateKey (dart:io-patch/secure_socket_patch.dart:152)
#2 main (file:///usr/local/www/www.revisortextos.pt/bin/main.dart:2105:10)
<asynchronous suspension>
#3 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:263)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:151)
I found the solution to the problem:
import 'dart:io';
import "dart:isolate";
main() {
SecurityContext context = new SecurityContext();
var chain = Platform.script.resolve('/etc/letsencrypt/live/www.example.com/fullchain.pem').toFilePath();
var key = Platform.script.resolve('/etc/letsencrypt/live/www.example.com/privkey.pem').toFilePath();
context.useCertificateChain(chain);
// Password not Required
context.usePrivateKey(key);
HttpServer.bindSecure(InternetAddress.ANY_IP_V4, 443, context).then((server) {
server.listen((HttpRequest request) {
request.response.write('Hello, world!');
request.response.close();
});
});
}
$ wget https://www.example.com/
--2017-10-31 14:51:29-- https://www.example.com/
Loaded CA certificate '/etc/ssl/certs/ca-certificates.crt'
Resolving www.example.com... xxx.xxx.xxx.xxx
Connecting to www.example.com|xxx.xxx.xxx.xxx|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: ‘index.html’
index.html [ <=> ] 5.06K --.-KB/s in 0s
2017-10-31 14:51:31 (11.2 MB/s) - ‘index.html’ saved [20589]

Xamarin Studio community treats handled exception as unhandled exception

I have this problem where I get unhandled exception crash on my Xamarin Android app. I'm trying to login user into parse.com using user session token. The statements are put inside try-catch block to catch exceptions. But catch block fails to catch "Invalid session token" error from parse.com and app crashes. Catch block works fine if I manually tamper sessionToken.
Here's what I am doing
try {
await ParseUser.BecomeAsync(sessionToken);
...
} catch (Exception e){
//log exception
}
when there is invalid session token error, above code crashes saying "unhandled exception...." even though it was put inside try block.
following code works. (manually tampering token)
try {
await ParseUser.BecomeAsync(sessionToken + "test");
...
} catch (Exception e){
//log exception
}
Parse component from Xamarin Component store
What am I missing?
Also, same code works just fine with Xamarin.iOS.
EDIT Adding StackTrace
at Parse.Internal.ParseCommandRunner+<>c__DisplayClass2.<RunCommandAsync>b__1 (System.Threading.Tasks.Task`1[TResult] t) [0x000eb] in <5d1c0c2b96a7483d85e5c63b3e156125>:0
at Parse.Internal.InternalExtensions+<>c__DisplayClass1`2[TIn,TResult].<OnSuccess>b__0 (System.Threading.Tasks.Task t) [0x00000] in <5d1c0c2b96a7483d85e5c63b3e156125>:0
at Parse.Internal.InternalExtensions+<>c__DisplayClass7`1[TResult].<OnSuccess>b__6 (System.Threading.Tasks.Task t) [0x0006f] in <5d1c0c2b96a7483d85e5c63b3e156125>:0
at System.Threading.Tasks.ContinuationResultTaskFromTask`1[TResult].InnerInvoke () [0x00024] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Threading.Tasks.Task.Execute () [0x00010] in <3fd174ff54b146228c505f23cf75ce71>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
at Parse.Internal.InternalExtensions+<>c__DisplayClass7`1[TResult].<OnSuccess>b__6 (System.Threading.Tasks.Task t) [0x00033] in <5d1c0c2b96a7483d85e5c63b3e156125>:0
at System.Threading.Tasks.ContinuationResultTaskFromTask`1[TResult].InnerInvoke () [0x00024] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Threading.Tasks.Task.Execute () [0x00010] in <3fd174ff54b146228c505f23cf75ce71>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
at Parse.Internal.InternalExtensions+<>c__DisplayClass7`1[TResult].<OnSuccess>b__6 (System.Threading.Tasks.Task t) [0x00033] in <5d1c0c2b96a7483d85e5c63b3e156125>:0
at System.Threading.Tasks.ContinuationResultTaskFromTask`1[TResult].InnerInvoke () [0x00024] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Threading.Tasks.Task.Execute () [0x00010] in <3fd174ff54b146228c505f23cf75ce71>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
at Hyphen_App.Droid.SplashActivity+<setCurrentUser>d__4.MoveNext () [0x00035] in /Chethan Shetty/GIT/android-parent/Hyphen_App.Droid/Splash/SplashActivity.cs:112
EDIT 1 After changing setCurrentUser to following, I am able to catch the exception but after 3-4 seconds app crashes by itself giving " System.AggregateException"
void setCurrentUser(string sessionToken,Action<bool> callback){
try {
ParseUser.BecomeAsync(sessionToken).Wait();
callback(true);
}catch(AggregateException e){
e.Handle( x => { return true; });
callback(false);
}
Like you said in the comments you were calling the async method in your OnCreate without awaiting it.
It can cause the Exception not to be caught, if the somewhere in the async stack a task is not awaited.
I hope it helped you resolve the issue.
Update
Sorry for not expressing me clearly. Your code must look something like that:
protected override async void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
await this.SetCurrentUser();
}
private async Task<bool> SetCurrentUser(string sessionToken)
{
try {
await ParseUser.BecomeAsync(sessionToken);
} catch (Exception e) {
return false;
}
}
to use the await keyword was what i was referring to when saying 'awaiting'.
With the async / await keywords in C#, callbacks are rarely used in asynchronous scenarios anymore. There is a short introduction over at microsoft docs

Resources