bnayagrawal
bnayagrawal

Reputation: 1154

Dart catch http exceptions

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.

Upvotes: 15

Views: 28316

Answers (2)

Suragch
Suragch

Reputation: 512566

This is a supplemental answer for other people searching for how to catch http exceptions.

It's good to catch each kind of exception individually rather than catching all exceptions generally. Catching them individually allows you to handle them appropriately.

Here is a code snippet adapted from Proper Error Handling in Flutter & Dart

// import 'dart:convert' as convert;
// import 'package:http/http.dart' as http;

try {
  final response = await http.get(url);
  if (response.statusCode != 200) throw HttpException('${response.statusCode}');
  final jsonMap = convert.jsonDecode(response.body);
} on SocketException {
  print('No Internet connection 😑');
} on HttpException {
  print("Couldn't find the post 😱");
} on FormatException {
  print("Bad response format 👎");
}

Upvotes: 22

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658007

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');
  }
}

Upvotes: 13

Related Questions