How do you catch canLaunch exceptions using url_launcher in flutter? - flutter

Using the code from the package I was unable to catch the exception. Note that I would like to catch this specific exception.
// from https://pub.dev/packages/url_launcher
_launchURL() async {
const url = 'myscheme://myurl';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
// my code
try {
_launchURL();
}
catch (e)
{
// although the exception occurs, this never happens, and I would rather catch the exact canLaunch exception
}

I would try to put the try catch statement inside the function. I believe what is happening is that the try/catch statement is only applying for the function call and although it is async I dont believe that it actually tries and returns exeptions.
So the solution would look somethink like this:
_launchURL() async {
try{
const url = 'myscheme://myurl';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
catch(e){
//debug e
}
}
// my code
launchURL();

You can use .then() for business logic.
For me, it is used to check if the app can be opened on the device.
Can be solution below,
--> url_launcher: ^6.0.2
--> https://pub.dev/packages/url_launcher
launch(appLink).then(
(bool isLaunch) {
print('isLaunch: $isLaunch');
if (isLaunch) {
// Launch Success
} else {
// Launch Fail
}
},
onError: (e) {
print('onError: $e');
},
).catchError(
(ex) => print('catchError: $ex'),
);
Work for me.

Future<void> _launch(String url) async {
await canLaunch(url)
? await launch(url)
: throw 'Could not launch $url';
}

Related

How to catch completeError from play?

I am checking the commit referenced here:
https://github.com/ryanheise/just_audio/issues/65
I am also facing the issue of the iOS browser not autoplaying and would like to catch the error. However the following does not seem to trigger the error:
try {
await player.play().onError((error, stackTrace));
} catch (e) {
print(e);
}
or
Future<void> playAudio() async {
try {
await player.play().catchError(onError);
} catch (e) {
print(e);
}
}
FutureOr<void> onError(error) {
print('ERROR DURING PLAY');
print(error); }
errors don't seem to show up in the console :(
How do I react to the completeError in the web imlementation? Sorry for the noob question. :) Thanks!

What is difference between _googleSignIn.signOut and _googleSignIn.disconnect in Flutter GoogleSignIn?

What is right usage or better way of under the two methods?
Method one
Future<bool> signout()async{
try {
await _googleSignIn.disconnect();
await _googleSignIn.signOut();
return true;
} catch (e) {
return false;
}
}
Method two
Future<bool> signout()async{
try {
await _googleSignIn.signOut();
return true;
} catch (e) {
return false;
}
}
Flutter Package Google_Sign_In
Difference between signout and disconnect is explain here :-
https://developers.google.com/identity/sign-in/android/disconnect
As my perspective this was better I use google signing my 8 apps and all are live on both stores I use this method everywhere
Future<bool> signout()async{
try {
await _googleSignIn.signOut();
return true;
} catch (e) {
return false;
}
}

Flutter custom exception not throwing

I upgraded Flutter from version 2.0.2 to version 2.2.2 and now the custom exceptions that are thrown from a Future function are not being catch.
For example, I got this Future function, where I call another Future that does a server request and returns back the response or throws a custom exception (ApiException) in case of error:
static Future<bool> signUpCustomerRequest(Map<String, dynamic> params) async {
try {
// Here we call this Future function that will do a request to server API.
dynamic _response = await _provider.signUpCustomer(params);
if (_response != null) {
updateUserData(_response);
return true;
}
return false;
} on ApiException catch(ae) {
// This custom exception is not being catch
ae.printDetails();
rethrow;
} catch(e) {
// This catch is working and the print below shows that e is Instance of 'ApiException'
print("ERROR signUpCustomerRequest: $e");
rethrow;
} finally {
}
}
And this is the Future function that does the request to server and throws the ApiException:
Future<User?> signUpCustomer(Map<String, dynamic> params) async {
// POST request to server
var _response = await _requestPOST(
needsAuth: false,
path: routes["signup_client"],
formData: params,
);
// Here we check the response...
var _rc = _response["rc"];
switch(_rc) {
case 0:
if (_response["data"] != null) {
User user = User.fromJson(_response["data"]["user"]);
return user;
}
return null;
default:
print("here default: $_rc");
// And here we have the throw of the custom exception (ApiException)
throw ApiException(getRCMessage(_rc), _rc);
}
}
Before upgrading to Flutter 2.2.2 the catch of custom exceptions worked perfectly. Did something change on this Flutter version? Am I doing something wrong?
Thanks!
I was able to reproduce your bug with the following code:
class ApiException implements Exception {
void printDetails() {
print("ApiException was caught");
}
}
Future<void> doSomething() async {
await Future.delayed(Duration(seconds: 1));
throw ApiException();
}
void main() async {
try {
await doSomething();
} on ApiException catch (ae) {
ae.printDetails();
} catch (e) {
print("Uncaught error: $e"); // This line is printed
}
}
There's an open issue on the dart sdk, which I think might be related, though I'm not sure: https://github.com/dart-lang/sdk/issues/45952.
In any case, I was able to correct the error by returning a Future.error, instead of throwing the error directly:
class ApiException implements Exception {
void printDetails() {
print("ApiException was caught"); // This line is printed
}
}
Future<void> doSomething() async {
await Future.delayed(Duration(seconds: 1));
return Future.error(ApiException());
}
void main() async {
try {
await doSomething();
} on ApiException catch (ae) {
ae.printDetails();
} catch (e) {
print("Uncaught error: $e");
}
}

on PlatformException catch is not working on version 2.2.2 of flutter

I'm working on a SignIn method using firebase
this is my code which been working just fine
try {
final auth = Provider.of<AuthBase>(context, listen: false);
if (_formType == EmailSignInFormType.signIn) {
await auth.signInWithEmailAndPassword(_email, _password);
} else {
await auth.createUserWithEmailAndPassword(_email, _password);
}
Navigator.of(context).pop();
} catch (e) {
PlatformAlertDialog(
title: 'Sign in failed',
content: e.toString(),
defaultActionText: 'OK',
).show(context);
}
and when I'm trying to improve my alert dialog by changing "catch (e)" to "on PlatformException catch (e)" with the same code as above, the exception handling brokes and the program stops working, when there is an exception.
I read the code of "PlatformException" and I figured out that it's not yet supporting null-safety and I'm guessing that this causes my problem, what do you think?
And is there any way to get the error message only using "catch (e)"
It worked by using on FirebaseAuthException catch (e) instead of on PlatformException catch (e)

How to catch http.get (SocketException)

I'm new to Flutter & Dart, trying to complete my first app.
I can't catch (with try-catch block) http.get SocketException (which happens when you call API and WiFi turned off)
I tried everything on the internet without luck, I even tried (Dio) package to catch this exception, but no success.
How to reproduce: use bottom code...turn off phone's WiFi...call API...now the app crashes with (SocketException) in your IDE.
Image: https://imgur.com/bA0rKEN
here is my simple code (updated)
RaisedButton(
child: Text("Call API"),
onPressed: () async {
try {
http.Response response = await getLoginResponse();
//do something with response
print(response.body);
} catch (e) {
print("Button onPressed Error: " + e.toString());
}
},
)
//---------------------------------------------------------------
Future<http.Response> getLoginResponse() {
return http.get(loginUrl).timeout(Duration(seconds: 10))
.then((response) {
return response;
}, onError: (e) {
print("onError: " + e.toString());
}).catchError((err) {
print("catchError: " + err.toString());
return null;
});
}
You can catch several types of errors and handle each one separately
Example:
import 'dart:io' as Io;
http.Client client = http.Client();
try {
response = await client.get(url).timeout(new Duration(seconds: 10));
} on Io.SocketException catch (_) {
throw Exception('Not connected. Failed to load data');
} on TimeoutException catch (_) {
throw Exception('Not connected. TimeOut Exception');
} catch (e) {
// Default error handling;
}
if you want to get catch in RaisedButton's try-catch block, instead of return null in getLoginInfo() methods, you must return an Exception like this:
Future<List<LoginObject>> getLoginInfo() async {
try {
List<LoginObject> loginObjectList = List<LoginObject>();
http.Response loginResponse =
await http.get(loginUrl).timeout(Duration(seconds: 10));
if (loginResponse.statusCode == 200) {
loginObjectList = loginObjectFromJson(loginResponse.body);
return loginObjectList;
} else {
throw Exception('Authentication Error');
}
} catch (e) {
print("Error: " + e.toString());
return throw Exception('Connection Error');;
}
}
Note: If you want to handle each one of error response, you can create an custom ErrorModelClass and handle error state with it and finally return your ErrorModelClass.
catch (error) {
print(error);
throw error is HttpResponseError ? error : HttpResponseError(0,"error connection");
HttpResponseError is my custom model class.