【问题标题】:Dart catch http exceptionsDart 捕获 http 异常
【发布时间】:2019-02-15 06:32:11
【问题描述】:

我正在使用 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' 永远不会打印在控制台上。我在这里做错了什么?我是飞镖新手。

【问题讨论】:

  • 使用async/await代替then,然后try/catch就可以了。
  • 能否请您提交代码sn-p。

标签: dart flutter


【解决方案1】:

这是其他人搜索如何捕获 http 异常的补充答案。

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

这是一个改编自Proper Error Handling in Flutter & Dart的代码sn-p

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

【讨论】:

  • 问题是 SocketException 是 dart::io 的一部分,但 dart::io 在 web 客户端上不可用(但 dart:http 可用)。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-15
    • 2019-12-31
    • 2013-07-28
    • 2018-07-07
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多