Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter- dart http library ClientException

I am doing a post request like this in flutter using HTTP dart package but sometimes when the network fails a ClientException is thrown from IOClient class but I don't get anything in catch block and app crashes.

http.post(url, headers: headers, body: body).then((response) {
  //response parsing
}).catchError((error) {
 //ClientException is never catched in this block.
});
like image 293
webianks Avatar asked Apr 09 '26 23:04

webianks


1 Answers

As mentioned in package:http/src/io_client.dart:

Any internal HTTP errors should be wrapped as [ClientException]s.

As mentioned in the docs this is a clear case of:

Potential problem: accidentally mixing synchronous and asynchronous errors

To resolve this issue, you need to wrap your code in Future.sync().

Future.sync() makes your code resilient against uncaught exceptions. If your function has a lot of code packed into it, chances are that you could be doing something dangerous without realizing it:

return new Future.sync(() {
  http.post(url, headers: headers, body: body).then((response) {});
});

Future.sync() not only allows you to handle errors you know might occur, but also prevents errors from accidentally leaking out of your function.

like image 167
Mahen Gandhi Avatar answered Apr 11 '26 13:04

Mahen Gandhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!