6.8 错误全局处理
实现步骤:
第 1 步:错题体数据结构
错误信息采用全局统一的数据格式
1 2 3 4 5
| { "statusCode": 400, "error": "registration-error-email-exists", "message": "已存在使用此电子邮件地址的帐户" }
|
statusCode
遵循 http status 标准
error
是一个错误文字标识
message
是错误描述,你可以显示给客户
第 2 步:错误数据 model
lib/common/models/error_message.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class ErrorMessageModel { int? statusCode; String? error; String? message;
ErrorMessageModel({ this.statusCode, this.error, this.message, });
factory ErrorMessageModel.fromJson(Map<String, dynamic> json) { return ErrorMessageModel( statusCode: json['statusCode'] as int?, error: json['error'] as String?, message: json['message'] as String?, ); }
Map<String, dynamic> toJson() => { 'statusCode': statusCode, 'error': error, 'message': message, }; }
|
第 3 步:dio 错误拦截
lib/common/services/wp_http.dart
1 2 3 4 5
| Future<void> _errorNoAuthLogout() async { Get.toNamed(RouteNames.systemLogin); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| @override Future<void> onError(DioError err, ErrorInterceptorHandler handler) async { final exception = HttpException(err.message); switch (err.type) { case DioErrorType.response: { final response = err.response; final errorMessage = ErrorMessageModel.fromJson(response?.data); switch (errorMessage.statusCode) { case 401: _errorNoAuthLogout(); break; case 404: break; case 500: break; case 502: break; default: break; } Loading.error(errorMessage.message); } break; case DioErrorType.other: break; case DioErrorType.cancel: break; case DioErrorType.connectTimeout: break; default: break; } err.error = exception; handler.next(err); }
|
如果 401
错误直接去登录页
打印错误信息给用户 Loading.error(errorMessage.message);
最后:运行
提交代码到 git