| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- import 'package:dio/dio.dart';
- /// API异常消息
- ///
- /// 当API访问出现错误时将会抛出[ApiException]异常,该异常对象包含[code]和[message]两个字段
- class ApiException implements Exception {
- final String _message;
- final String _code;
- ApiException(
- this._code,
- this._message,
- );
- String get message => _message;
- String get code => _code;
- @override
- String toString() {
- return "$_code, $_message";
- }
- factory ApiException.http(DioException e) {
- switch (e.type) {
- case DioExceptionType.cancel:
- return ApiException("-1", "请求取消");
- case DioExceptionType.connectionTimeout:
- return ApiException("-1", "连接超时");
- case DioExceptionType.sendTimeout:
- return ApiException("-1", "请求超时");
- case DioExceptionType.receiveTimeout:
- return ApiException("-1", "响应超时");
- case DioExceptionType.badResponse:
- try {
- int? errCode = e.response!.statusCode;
- switch (errCode) {
- case 400:
- return ApiException(errCode!.toString(), "请求语法错误");
- case 401:
- return ApiException(errCode!.toString(), "没有权限");
- case 403:
- return ApiException(errCode!.toString(), "服务器拒绝执行");
- case 404:
- return ApiException(errCode!.toString(), "无法连接服务器");
- case 405:
- return ApiException(errCode!.toString(), "请求方法被禁止");
- case 500:
- return ApiException(errCode!.toString(), "服务器内部错误");
- case 502:
- return ApiException(errCode!.toString(), "无效的HTTP请求");
- case 503:
- return ApiException(errCode!.toString(), "服务器没有响应");
- case 505:
- return ApiException(errCode!.toString(), "不支持HTTP协议请求");
- default:
- return ApiException(
- errCode!.toString(), e.response!.statusMessage!);
- }
- } catch (_) {
- return ApiException("-1", "未知错误");
- }
- default:
- return ApiException("-1", e.message ?? '');
- }
- }
- }
|