Dart捕获HTTP异常

时间:2019-02-15 06:32:11

标签: dart flutter

我正在使用dart的http程序包发出发布请求。由于某些服务器问题,其抛出异常。我已经将代码包装在try catch块代码中,但是没有捕获异常。

这是发出网络请求的代码

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

使用上述静态方法的单独类的功能。

void onButtonClick() {

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

在上述方法中,永远不会捕获异常。 “ WTF”从不打印在控制台上。我在这里做错了什么?我是飞镖新手。

2 个答案:

答案 0 :(得分:1)

这是对其他寻求如何捕获http异常的其他人的补充答案。

最好单独捕获每种异常,而不是一般捕获所有异常。单独捕获它们可以使您适当地处理它们。

这是改编自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 ?");
}

答案 1 :(得分:0)

使用async / await代替then,然后try / catch会起作用

void onButtonClick() async {
  try {
    var value = await VerificationService.requestOtp(PhoneNumberPost(phone))
  } catch(_) {
    enableInputs();
    print('WTF');
  }
}
相关问题