error_handle.dart 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import 'dart:io';
  2. import 'package:dio/dio.dart';
  3. class ExceptionHandle {
  4. static const int success = 200;
  5. static const int success_not_content = 204;
  6. static const int unauthorized = 401;
  7. static const int forbidden = 403;
  8. static const int not_found = 404;
  9. static const int net_error = 1000;
  10. static const int parse_error = 1001;
  11. static const int socket_error = 1002;
  12. static const int http_error = 1003;
  13. static const int timeout_error = 1004;
  14. static const int cancel_error = 1005;
  15. static const int unknown_error = 9999;
  16. static NetError handleException(dynamic error){
  17. print(error);
  18. if (error is DioError){
  19. if (error.type == DioErrorType.DEFAULT ||
  20. error.type == DioErrorType.RESPONSE){
  21. dynamic e = error.error;
  22. if (e is SocketException){
  23. return NetError(socket_error, "网络异常,请检查你的网络!");
  24. }
  25. if (e is HttpException){
  26. return NetError(http_error, "服务器异常!");
  27. }
  28. return NetError(net_error, "网络异常,请检查你的网络!");
  29. }else if (error.type == DioErrorType.CONNECT_TIMEOUT ||
  30. error.type == DioErrorType.SEND_TIMEOUT ||
  31. error.type == DioErrorType.RECEIVE_TIMEOUT){
  32. return NetError(timeout_error, "连接超时!");
  33. }else if (error.type == DioErrorType.CANCEL){
  34. return NetError(cancel_error, "取消请求");
  35. }else{
  36. return NetError(unknown_error, "未知异常");
  37. }
  38. }else {
  39. return NetError(unknown_error, "未知异常");
  40. }
  41. }
  42. }
  43. class NetError{
  44. int code;
  45. String msg;
  46. NetError(this.code, this.msg);
  47. }