Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart catch http exceptions

Tags:

flutter

dart

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.

like image 373
bnayagrawal Avatar asked Feb 15 '19 06:02

bnayagrawal


People also ask

How do you catch an exception in darts?

The try / on / catch Blocks The catch block is used when the handler needs the exception object. The try block must be followed by either exactly one on / catch block or one finally block (or one of both). When an exception occurs in the try block, the control is transferred to the catch.

Which is used to disrupt the execution in Dart?

Exception is a runtime unwanted event that disrupts the flow of code execution.


2 Answers

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 👎");
}
like image 154
Suragch Avatar answered Oct 18 '22 20:10

Suragch


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');
  }
}
like image 39
Günter Zöchbauer Avatar answered Oct 18 '22 19:10

Günter Zöchbauer