Dart 捕获 http 异常

bna*_*wal 10 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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

使用上述静态方法的单独类的函数。

void onButtonClick() {

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

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

Gün*_*uer 8

使用async/await而不是then,然后try/catch将起作用

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


Sur*_*gch 8

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

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

这是改编自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 ");
}
Run Code Online (Sandbox Code Playgroud)

  • 问题是 SocketException 是 dart::io 的一部分,但 dart::io 在 Web 客户端上不可用(但 dart:http 可用)。 (2认同)