我正在使用 dart 的 http 包来发出发布请求。由于某些服务器问题,它会抛出异常。我已将代码包装在 try catch block 代码中,但它没有捕获异常。
这是发起网络请求的代码
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”永远不会打印在控制台上。我在这里做错了什么?我是 Dart 的新手。
最佳答案
这是对其他搜索如何捕获 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 👎");
}
关于Dart 捕获 http 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54703788/