so I was trying to see how to handle the possibility of my server being down for whatever reason, and I keep getting HTTPLinkServerException without being able to handle it with a try/catch block.
After seing the answer here try catch on HttpLinkServerException doesn't catch error
I also wrote my own error parser, but still doesn't work, since the exception is being thrown because of the HTTP status code. Any thoughts?
Is there something I'm missing on how to catch errors from async* functions? (I'm sort of new to flutter/dart)
The part of my code that triggers the error is this:
try {
final result = graphQLClient.mutate(
MutationOptions(
document: gql(myMutation),
variables: <String, String>{
"var": val,
},
)
);
} catch(err) {
print(err);
}
Thanks!
Related
So I have a method that uses the Flutter HTTP library and is responsible for calling HTTP requests to the server with code like this:
Future<List<DataModel>> fetchData() async {
try {
var url = Uri.parse('${baseUrlParse}myapipath');
var request = await http.get(url);
var data = jsonDecode(request.body);
return data;
} catch (e) {
print('Catch ${e}');
rethrow;
}
}
This code runs fine and has no issues.
It got to the point where when I have no internet connection or server connection fails, the app freezes, and an error file appears (if you're debugging in VS Code), called http_impl.dart, and the error snippet goes something like this:
onError: (error) {
// When there is a timeout, there is a race in which the connectionTask
// Future won't be completed with an error before the socketFuture here
// is completed with a TimeoutException by the onTimeout callback above.
// In this case, propagate a SocketException as specified by the
// HttpClient.connectionTimeout docs.
if (error is TimeoutException) {
assert(connectionTimeout != null);
_connecting--;
_socketTasks.remove(task);
task.cancel();
throw SocketException(
"HTTP connection timed out after $connectionTimeout, "
"host: $host, port: $port");
}
_socketTasks.remove(task);
_checkPending();
throw error;
});
I have tried to implement from this source and this, but when I make a request but have no connection, this error still occurs.
How to deal with this problem?
What I want is, if there is a problem with HTTP either there is no connection, or it fails to contact the server, then I can make a notification..
Is there something wrong with my code?
Please help, thank you
You re throw the exception in your code,
You need to catch exception where you call to this method like this.
try {
await fetchData();
} catch (e) {
// TODO: handle exception
}
You can stop VS Code catching unhandled exceptions from this way
https://superuser.com/a/1609472
In my Flutter app I can't get the try/catch part to work properly.
Future<void> getTime() async {
try {
Response response = await get(Uri.parse('https://api.api-ninjas.com/v1/worldtime?city=$location'),
// provoke an error
headers: {'Api_Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'},
);
Map data = jsonDecode(response.body);
time = "${data['hour']}h - ${data['minute']}m - ${data['second']}s";
}
catch (e) {
print('caught error: $e');
time = 'could not get time data';
}
}
It looks like the catch section is not reached.
Any idea ?
I guess the issue here is that try-catch blocks do not play well with async operations, in order to be able to catch errors in that context please refer to runZonedGuarded, it will encapsulate all method calls and listen to any exception thrown + handle them in a way just like catch does
myCrashingFunc() {
var a = [];
print(a[0]);
}
try {
myCrashingFunc()
} catch (e) {
print(StackTrace.current.toString());
}
Actually, when I debug, I let everything crash so my StackTrace get me to the crashing line.
When I send my app in prod, I use try catch so new errors have default behavior handle.
Problem: with try catch, my Stacktrace stop in the catch, I would like to see the StackTrace give me insigh of the try. (ex: here my StackTrace will only go to the line print(StackTrace.current.toString());
Question: How can I get StackTrace of the function in the try. (ex: hre I would like to see my StackTrace go to line print(a[0]);)
You can access the stacktrace if you pass it as the second argument to catch as follows:
myCrashingFunc() {
var a = [];
print(a[0]);
}
try {
myCrashingFunc()
} on Exception catch (e, s) {
print(s);
}
I am purposely causing this error.
var response = await http.post(url,headers: {"Content-Type": "application/x-www-form-urlencoded"},body: args); //die here
//not continues
print(response);
I have turned off the execution of my server, so the web request cannot be executed. I want to know how I can control this error, since the application dies at this point.
how can I do it?
To catch an exception, you need to wrap the line that causes it with a try/catch block :
try {
var response = http.post(url);
}
catch(exception){
print(exception);
}
Given the shortcode example below:
...
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} on Exception catch (_) {
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
I would expect the catch block to execute whenever the decoding fails. However, when a bad response returns, the terminal displays the exception and neither the catch nor the continuation code fires...
flutter: 1 parsing stuff
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: type
'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type
'List<dynamic>'
What am I missing here?
Functions can throw anything, even things that aren't an Exception:
void foo() {
throw 42;
}
But the on Exception clause means that you are specifically catching only subclass of Exception.
As such, in the following code:
try {
throw 42;
} on Exception catch (_) {
print('never reached');
}
the on Exception will never be reached.
It is not a syntax error to have on Exception catch as someone else answered. However you need to be aware that the catch will not be triggered unless the error being thrown is of type Exception.
If you want to find out the exact type of the error you are getting, remove on Exception so that all errors are caught, put a breakpoint within the catch and check the type of the error. You can also use code similar to the following, if you want to do something for Exceptions, and something else for errors of all other types:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
Use:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
The rule is that exception handling should be from detailed exceptions to general exceptions in order to make the operation to fall in the proper catch block and give you more information about the error, like catch blocks in the following method:
Future<int> updateUserById(int userIdForUpdate, String newName) async {
final db = await database;
try {
int code = await db.update('tbl_user', {'name': newName},
whereArgs: [userIdForUpdate], where: "id = ?");
return code;
}
on DatabaseException catch(de) {
print(de);
return 2;
}
on FormatException catch(fe) {
print(fe);
return 2;
}
on Exception catch(e) {
print(e);
return 2;
}
}
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} catch (_) { . // <-- removing the on Exception clause
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
This works, but what is the rationale behind this? Isn't the type inconsistency an Exception?
As everybody or most of the people said, try to know exactly what error you are getting:
try{
}
catch(err){
print(err.runTimeType);
}
runTimeType will give you the type of data or exception you are getting or to put simple the exception itself.
And then do whatever you want. (Like if you are not getting the exception of what you expected, then try to fix that issue or change the exception.)
Another option is to go with general form.
Using the simple catch which will prompt every time.
The other possible reason for the catch bloc not to fire, as pointed out in this question, is missing brackets when throwing an exception.
Must write throw FormatException() instead of throw FormatException.
I had a issue with try catch but my problem was the API that I send http request, doesn't response of my request so that is why my request doesn't response anything and try catch didn't catch the error. So I suggest you to add timeout to your request so that if your api doesn't response your request after a while you can cancel your request with timeout. Here is an example how to use it;
try {
final response = await http.post(Url).timeout(Duration(seconds: 5));
} catch (error) {
print(error)
}