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!
Related
This is the code I want to avoid repeating. If possible also try block.
try {
//
} on TimeoutException catch (e) {
log('Timeout Error: $e');
rethrow;
} on SocketException catch (e) {
log('Socket Error: $e');
rethrow;
} on Error catch (e) {
log('General Error: $e');
rethrow;
} catch (e) {
log('All other Errors: $e');
rethrow;
}
You could define a function like:
void tryCatch(Function f) {
try {
f();
} on TimeoutException catch (e) {
log('Timeout Error: $e');
rethrow;
} on SocketException catch (e) {
log('Socket Error: $e');
rethrow;
} on Error catch (e) {
log('General Error: $e');
rethrow;
} catch (e) {
log('All other Errors: $e');
rethrow;
}
}
and then anywhere you want to use it do
tryCatch((){
//your code here
});
One trivial answer could be to refactor that try-catch cascade in a dedicated function or class, in which you return the value if everything's all right, or handle the corresponding error.
I guess yours is just an example code, but if you're just interested in logging an error and then rethrow, you don't need to distinguish between those exceptions and errors.
You can easily retrieve your error's type like so:
try {
// some risky code
} catch(error, stackTrace) {
print(error.runtimeType);
print(error); // calls its internal toString() method
rethrow;
}
Even the above example could be refactored in a dedicated function or class, by the way.
If you're looking into something even more specific let me know, because I'm kinda curious about this, too.
My code is trying to communicate using Socket, but I can't seem to catch the exception.
I've tried these things, but they don't work and I get an exception on the IDE.
Socket socket;
try {
socket = await Socket.connect(ip, port);
// Instead of jumping to errorProcess(), the IDE will show an exception here...
} catch(e) {
errorProcess(e);
}
Socket socket = await Socket.connect(ip, port).catchError((e) {
errorProcess(e);
// catchError says we need to return FutureOr<Socket>...
});
How can I catch exceptions?
Try adding SocketException for your try catch statement.
Example Code:
try {} on SocketException catch (e) {
print(e);
} catch (e) {
print(e);
}
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)
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.
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';
}