api_exception.dart 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import 'package:dio/dio.dart';
  2. /// API异常消息
  3. ///
  4. /// 当API访问出现错误时将会抛出[ApiException]异常,该异常对象包含[code]和[message]两个字段
  5. class ApiException implements Exception {
  6. final String _message;
  7. final String _code;
  8. ApiException(
  9. this._code,
  10. this._message,
  11. );
  12. String get message => _message;
  13. String get code => _code;
  14. @override
  15. String toString() {
  16. return "$_code, $_message";
  17. }
  18. factory ApiException.http(DioException e) {
  19. switch (e.type) {
  20. case DioExceptionType.cancel:
  21. return ApiException("-1", "请求取消");
  22. case DioExceptionType.connectionTimeout:
  23. return ApiException("-1", "连接超时");
  24. case DioExceptionType.sendTimeout:
  25. return ApiException("-1", "请求超时");
  26. case DioExceptionType.receiveTimeout:
  27. return ApiException("-1", "响应超时");
  28. case DioExceptionType.badResponse:
  29. try {
  30. int? errCode = e.response!.statusCode;
  31. switch (errCode) {
  32. case 400:
  33. return ApiException(errCode!.toString(), "请求语法错误");
  34. case 401:
  35. return ApiException(errCode!.toString(), "没有权限");
  36. case 403:
  37. return ApiException(errCode!.toString(), "服务器拒绝执行");
  38. case 404:
  39. return ApiException(errCode!.toString(), "无法连接服务器");
  40. case 405:
  41. return ApiException(errCode!.toString(), "请求方法被禁止");
  42. case 500:
  43. return ApiException(errCode!.toString(), "服务器内部错误");
  44. case 502:
  45. return ApiException(errCode!.toString(), "无效的HTTP请求");
  46. case 503:
  47. return ApiException(errCode!.toString(), "服务器没有响应");
  48. case 505:
  49. return ApiException(errCode!.toString(), "不支持HTTP协议请求");
  50. default:
  51. return ApiException(
  52. errCode!.toString(), e.response!.statusMessage!);
  53. }
  54. } catch (_) {
  55. return ApiException("-1", "未知错误");
  56. }
  57. default:
  58. return ApiException("-1", e.message ?? '');
  59. }
  60. }
  61. }