gpt4 book ai didi

flutter - Dio 不会捕获错误并卡在抛出自定义异常

转载 作者:行者123 更新时间:2023-12-05 08:03:29 28 4
gpt4 key购买 nike

这是我的拦截器 onError 代码。我正在尝试使用自定义异常类抛出自定义异常

 @override
Future<void> onError(DioError err, ErrorInterceptorHandler handler) async {

switch (err.type) {
case DioErrorType.connectTimeout:
case DioErrorType.sendTimeout:
case DioErrorType.receiveTimeout:
throw DeadlineExceededException(err.requestOptions);
case DioErrorType.response:
switch (err.response?.statusCode) {
case 400:
throw BadRequestException(err.requestOptions);
case 401:
throw UnauthorizedException(err.requestOptions);

case 404:
throw NotFoundException(err.requestOptions);
case 409:
throw ConflictException(err.requestOptions);
case 500:
throw InternalServerErrorException(err.requestOptions);
}
break;
case DioErrorType.cancel:
break;
case DioErrorType.other:
throw NoInternetConnectionException(err.requestOptions);
}
// super.onError(err, handler);
return handler.next(err);
}

我无法 catch 卡在抛出自定义异常上的这部分指针

static requestMyJobs() async {
try {
print('---------job calling api---------');
var response = await ApiBase.dio.get(ApiLinks.getMyJobsLink);
print('Status code ${response.statusCode}');
var jocodedData = response.data['data'];
return jocodedData.map<MyJobs>((json) => MyJobs.fromJson(json)).toList();
} on UnauthorizedException catch (f) {
print("-Exception----------------");

}
}

最佳答案

首先,您的自定义异常类应该从 DioError 类扩展。

例如,这是我创建的自定义异常之一:

class ConnectionException extends DioError {
ConnectionException({required super.requestOptions});
}

然后不在 onError 方法中抛出异常,而是调用 super.onError(CustomException, handler);

这是我做的:

  @override
Future onError(
DioError err,
ErrorInterceptorHandler handler,
) async {
switch (err.type) {
case DioErrorType.connectTimeout:
case DioErrorType.receiveTimeout:
case DioErrorType.sendTimeout:
throw TimeoutException();
case DioErrorType.response:
switch (err.response?.statusCode) {
case 400:
super.onError(BadRequestException(err.response?.data, requestOptions: err.requestOptions), handler);
break;
case 401:
super.onError(UnAuthorizedException(requestOptions: err.requestOptions), handler);
break;
case 403:
try {
await refreshToken();
await retryRequest(err.requestOptions);
} catch (_) {
super.onError(UnAuthorizedException(requestOptions: err.requestOptions), handler);
}
break;
case 500:
super.onError(InternalServerException(requestOptions: err.requestOptions), handler);
break;
}
break;
case DioErrorType.other:
super.onError(ConnectionException(requestOptions: err.requestOptions), handler);
break;
default:
super.onError(err, handler);
}
}

关于flutter - Dio 不会捕获错误并卡在抛出自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72667780/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com