Home > Back-end >  Flutter&Dart Catch Block does not catch thrown Exception
Flutter&Dart Catch Block does not catch thrown Exception

Time:05-06

I am trying to catch thrown exception when server does not return 200 status code. Here is the code:

late Future<List<Data>> datasFuture;
String _warning = "";

@override
void initState() {
  try {
    datasFuture = RestfulServiceProvider.fetchDatas();
  } on Exception {
    _warning = "There is no data to fetch!";
  }
  super.initState();
}

//RestfulServiceProvider class
static Future<List<Data>> fetchDatas() async {
List jsonResponse = [];
final response =
    await http.get(Uri.parse('http://localhost:8080/datas'));

if (response.statusCode == 200) {
  jsonResponse = json.decode(response.body);
  return jsonResponse.map((data) => Data.fromJson(data)).toList();
} else {
  throw Exception();
}

}

When exception occurs code does not go in on Exception block, I cant handle the error. Any idea or solutions? thanks.

CodePudding user response:

Try-catch block can catch exceptions occured in the bounds of its block. Your will not catch error because you are just assigning Future to a variable ( not awaiting its value ). So can the block catch exceptions from single assignment operation? No. Variable is just assigned and the program moves on and quits try-catch block immediately. You must await the value to catch it the block - awaiting it. But you can not use async-await syntax directly inside initState. So you have 2 options:

  1. catchError of Future

    RestfulServiceProvider.fetchDatas().catchError((error){Your code here})); 
  2. Utilizing it into another function with async-await

     void someFunc () async{
              try {
         await RestfulServiceProvider.fetchDatas();
       } on Exception catch(e) {
         _warning = "There is no data to fetch!";
       }
    
    }
    

And call it in initState

  • Related