Dart catch http exceptions

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

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 👎");
}

Tags:

Dart

Flutter