您可以按以下方式正确处理 dio 错误
try {
Response response = await allDataRepository.getData();
print(response.toString());
} on DioError catch (dioError) {
print(dioError);
if (dioError.type == DioErrorType.response) {
switch (dioError.response!.statusCode) {
case 404:
log(error: '400 - Not found');
break;
case 401:
log(error: '401 - Unauthorized.');
break;
case 500:
log(error: '500 - Internal Server Error.');
break;
case 501:
log(error: '501 - Not Implemented Server Error.');
break;
case 502:
log(error: '502 - Bad Gateway Server Error.');
break;
default:
log(error: '${dioError.response!.statusCode} - Something went wrong while trying to connect with the server');
break;
}
} else if (dioError.type == DioErrorType.other) {
log(error: 'Please check your internet connection. Try again switching to a different connection');
}
} catch (e) {
log(error: 'Something went wrong : $e');
}
存储库应如下所示(data_repository.dart)
class DataRepository {
final HttpClient httpClient;
DataRepository({required this.httpClient});
Future<Response> getData() async {
Response response = await httpClient.dio.get(
GlobalConfig.getDataUrl,
);
return response;
}
}
HttpClient 应该看起来像这样 (http_client.dart)
class HttpClient {
final Dio dio;
HttpClient({required this.dio});
static final String basePath = GlobalConfig.baseUrl;
void addBasePathInterceptor() {
dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
print(options.uri);
if (!options.path.startsWith("http")) {
options.baseUrl = basePath;
}
return handler.next(options);
},
));
addUrlInterceptor();
// addVersionInterceptor();
}
Interceptor? sessionCookieInterceptor;
Interceptor? versionCookieInterceptor;
Interceptor? status401Interceptor;
// void addSessionCookieInterceptor(List<String> cookies) {
// sessionCookieInterceptor = InterceptorsWrapper(
// onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
// options.headers['cookie'] = cookies.join(';');
// });
// dio.interceptors.add(sessionCookieInterceptor!);
// }
// void addVersionInterceptor() {
// versionCookieInterceptor = InterceptorsWrapper(
// onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
// options.headers['website-version'] = '26.3.0';
// });
// dio.interceptors.add(versionCookieInterceptor!);
// }
void addUrlInterceptor() {
dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
print('onRequest ${options.uri}');
return handler.next(options);
},
onResponse: (Response response, ResponseInterceptorHandler handler) {
print('onResponse ${response.statusCode} ${response.realUri}');
return handler.next(response);
},
onError: (DioError error, ErrorInterceptorHandler handler) {
if (error.type == DioErrorType.response) {
print('------------------------');
print(error.error);
print(error.response?.realUri);
print(error.response?.statusCode);
print(error.response?.data);
print('------------------------');
}
return handler.next(error);
},
));
}
void add401Interceptor() {
print("Adding 401 interceptor");
status401Interceptor = InterceptorsWrapper(
onError: (DioError res, ErrorInterceptorHandler handler) {
if (res.response != null && res.response?.statusCode == 401) {
// globalBloc.add(ShowErrorSnackBar(
// error: 'You have been logged out, Please login again'));
// authenticationBloc.add(AuthenticationUnauthenticatedEvent());
// mainBloc.add(LougoutEvent());
}
return handler.next(res);
});
dio.interceptors.add(status401Interceptor!);
}
// void remove401Interceptor() {
// dio.interceptors.remove(status401Interceptor);
// }
}
最后,在 main.dart 中初始化 HttpClient 如下
void main() async {
// Intializing Http Client
HttpClient(dio: sl()).addBasePathInterceptor();
runApp(MyApp());
}
请注意,您只需要以下一堆代码。但我已经描述了一种处理应用程序中每个 API 调用的好方法。
Dio dio = new Dio();
try {
Response response = await dio.get(GlobalConfig.getDataUrl);
print(response.toString());
} on DioError catch (dioError) {
print(dioError);
if (dioError.type == DioErrorType.response) {
switch (dioError.response!.statusCode) {
case 404:
log(error: '400 - Not found');
break;
case 401:
log(error: '401 - Unauthorized.');
break;
case 500:
log(error: '500 - Internal Server Error.');
break;
case 501:
log(error: '501 - Not Implemented Server Error.');
break;
case 502:
log(error: '502 - Bad Gateway Server Error.');
break;
default:
log(error: '${dioError.response!.statusCode} - Something went wrong while trying to connect with the server');
break;
}
} else if (dioError.type == DioErrorType.other) {
log(error: 'Please check your internet connection. Try again switching to a different connection');
}
} catch (e) {
log(error: 'Something went wrong : $e');
}