0

I want check if Api Url Statuscode is 200 , everything is ok untill in else statement .
I Got this error

Exception has occurred.
_Exception (Exception: Failed Load Data)

It's My Code Api

Future<List<Mosque>> getMahasiswaById(String id) async {
  var baseURL=Urls.BASE_API_URL;
  var apiRespon = await http.get('$baseURL/mahasiswa/get/id/$id');
  if(apiRespon.statusCode == 200) {
    final apiResponJson = json.decode(apiRespon.body);
    print(apiResponJson);
    return (apiResponJson['data'] as List).map((p)=>Mosque.fromJson(p)).toList();
  } else {
    throw Exception('Failed Load Data');
  }
}

How can i fix this ? Thanks

1 Answer 1

1

always use try and catch with http requests it'll help you to identify the source of the exception , you can do something like that :

Future<List<Mosque>> getMahasiswaById(String id) async{
    var baseURL=Urls.BASE_API_URL;
    try{
    var apiRespon = await http.get('$baseURL/mahasiswa/get/id/$id');
   if(apiRespon.statusCode == 200){
      final apiResponJson = json.decode(apiRespon.body);
      print(apiResponJson);
      return (apiResponJson['data'] as List).map((p)=>Mosque.fromJson(p)).toList();
      }
     else {
         print(apiReson.statusCode.toString());
         throw Exception('Failed load data with status code ${apiReson.statusCode}');   
   }
  catch(e){ 
       print (e); 
       throw e;}
 }

most of the time the exceptions come from bad internet connection , issue in the back end or lost in the internet connection ,when you use the above code it'll print out the type of the exception so you can identify the root of the error. I hope that can help

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.