How to deal with HTTP connection timed out crashes in Flutter - flutter

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

Related

Flutter can't catch errors

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

Make promise calls with a fixed timeout

I am currently trying to make it check for a database connection. but it seems like the result, ie connection is pending.
I am looking to impliment a system where i can send an timeout input, where the promise would be rejected due to a fixed timeout.
Something like;
try {
start(timeout: 6000) // 6 secs timeout on promise. default, ie no params: 3sec
} catch(e) {
// failed due to, in this case, timeout, since there is no connection running, and the database is pending their promise.
}
How can i accomplish such timeout?
current running example gives the following:
connected to mongo Promise { <pending> }
starting server code:
const start = async () => {
console.log("connecting to database");
try {
console.log("Attempting to establish connection....");
var result = await mongoose.connect('mongodb://localhost/db',{useNewUrlParser: true});
console.log("connected to mongo",result);
return result;
} catch (error) {
console.log("failed to connect to mongo",error);
}
}
try {
start();
} catch(e) {
console.log("failed to start server",e);
throw new Error("failed to start server",e);
}

How to avoid connection errors to an api in flutter? (breakpoint type appears in VS code)

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);
}

Flutter and Dart try catch—catch does not fire

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)
}

Nodejs: How to catch exception in net.createServer.on("data",...)?

I've got a standard socket-server (NO HTTP) setup as follows (contrived):
var server = net.createServer(function(c) { //'connection' listener
c.on('data', function(data) {
//do stuff here
//some stuff can result in an exception that isn't caught anywhere downstream,
//so it bubbles up. I try to catch it here.
//this is the same problem as just trying to catch this:
throw new Error("catch me if you can");
});
}).listen(8124, function() { //'listening' listener
console.log('socket server started on port 8124,');
});
Now the thing is I've got some code throwing errors that aren't catched at all, crashing the server. As a last measure I'd like to catch them on this level, but anything I've tried fails.
server.on("error",....)
c.on("error",...)
Perhaps I need to get to the socket instead of c (the connection), although I'm not sure how.
I'm on Node 0.6.9
Thanks.
process.on('uncaughtException',function(err){
console.log('something terrible happened..')
})
You should catch the Exceptions yourself. There is no event on either connection or server objects which would allow you to handle exception the way you described. You should add exception handling logic into your event handlers to avoid server crash like this:
c.on('data', function(data) {
try {
// even handling code
}
catch(exception) {
// exception handling code
}