Search code examples
flutterdartexceptiontry-catchflutter-http

Flutter http exception not throw on another try catch block


I get into this weird exception which keeps on coming and freezing my app.
I am try to handle SocketException and TimeOutException in http package with provider package.

class Auth with ChangeNotifier{
..........
Future<User> getUser(String id) async {
try {
final user = (await http.post("${Domain.ADDRESS}/user",
      headers: {"auth-token": _token}, body: {"userId": id}))
  .body;
 } on SocketException {
 throw HttpException("DISCONNECTED");
 } on TimeoutException {
 throw HttpException("TIMEOUT");
}  catch (error) {
 print(error);
  throw HttpException("SOMETHING_WENT_WRONG");
  }
 notifyListeners();
 return userdata;
 }
   ......
 }

when internet in not connected application freezing at

on SocketException {
throw HttpException("DISCONNECTED");  <------------ Exception has occurred.
                                                  HttpException (DISCONNECTED)

But I handle this on next screen

 @override
  Future<void> didChangeDependencies() async {
 ......

 setState(() {
 isLoading = true;
 });
 try{
   user= await Provider.of<Auth>(context)
  .getUser(Provider.of<Auth>(context).userId);
 if (this.mounted) {
  setState(() {
    isLoading = false;
  });
    }
 
    }on HttpException catch(error){
    if(error.toString().contains("DISCONNECTED")){
        Scaffold.of(context).showSnackBar(SnackBar(content: Text("Please check your internet 
 connection"),));
    }
   }catch(error){
     print(error);
   }
  super.didChangeDependencies();
}

Custom HttpException.dart

class HttpException implements Exception {
final String message;
HttpException(this.message);
@override
String toString() {
return message;
}
}

Solution

  • So if I understand you right, your IDE pauses when the exception is thrown, even though you catch it correctly.

    Can you tell me what happens after resuming / unpausing the IDE that you're using, does it behave as expected and print this?

    if(error.toString().contains("DISCONNECTED")){
            Scaffold.of(context).showSnackBar(SnackBar(content: Text("Please check your internet 
     connection"),));
    

    Because if it does, that means that you probably have the Breakpoints setting on All Exceptions and not only Uncaught Exceptions.

    Image of visual code run tab