【发布时间】: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。