Dart catch http exceptions

Question

Asked by bnayagrawal on February 15, 2019 (source).

I am using http package of dart to make post requests. Due to some server issues its throwing exception. I have wrapped the code in a try catch block code but it's not catching the exception.

Here's the code which makes network request

  class VerificationService {

  static Future<PhoneVerification> requestOtp(
      PhoneNumberPost phoneNumberPostData) async {
    final String postData = jsonEncode(phoneNumberPostData);
    try {
      final http.Response response = await http.post(
        getPhoneRegistrationApiEndpoint(),
        headers: {'content-type': 'Application/json'},
        body: postData,
      );
      if(response.statusCode == 200) {
        return PhoneVerification.fromJson(json.decode(response.body));
      } else {
        throw Exception('Request Error: ${response.statusCode}');
      }
    } on Exception {
      rethrow;
    }
  }
}

A function of a separate class using the above static method.

void onButtonClick() {

try {
    VerificationService.requestOtp(PhoneNumberPost(phone))
        .then((PhoneVerification onValue) {
      //Proceed to next screen
    }).catchError((Error onError){
      enableInputs();
    });
  } catch(_) {
    print('WTF');
  }
}

In the above method, the exception is never caught. 'WTF' is never printed on the console. What am I doing wrong here? I am new to dart.

Answer

Question answered by Günter Z (source).

Use async/await instead of then, then try/catch will work

void onButtonClick() async {
  try {
    var value = await VerificationService.requestOtp(PhoneNumberPost(phone))
  } catch(_) {
    enableInputs();
    print('WTF');
  }
}
DART FLUTTER
SHARE: