Flutter错误解析插件api_error_parser的使用
Flutter错误解析插件api_error_parser的使用
API Parser
A library for parsing responses from api and converting error codes into messages for the user.
API响应描述
假定响应将符合以下规范。
每个来自服务器的错误应该以以下格式出现:
code
: 错误的唯一代码。用于从字典中识别错误。target
: 某种错误范围。可选值为:field
- 错误与某个字段相关,common
- 错误与整个请求相关。- `message (可选): 开发者的错误消息(仅用于调试目的)
- **
source (可选)**: 附加数据的容器。任意结构:(字段:资源对象属性名称。如果目标设置为
field`,则必需)
示例:
{
"data": [
{
"id": 1,
"userName": "Tom",
"age": 21
},
{
"id": 2,
"userName": "Bob",
"age": 22
}
],
"errors": [
{
"code": "insufficient_funds",
"target": "common",
"message": "Hi Nick, it seems that user has empty balance"
},
{
"code": "invalid_punctuation",
"target": "field",
"source": "userPassword",
"message": "Hi Vova, it seems that the password provided is missing a punctuation character"
},
{
"code": "invalid_password_confirmation",
"target": "field",
"source": {
"field": "userPassword",
"someAdditionalData": "bla bla bla"
},
"message": "Hi Lesha, it seems that the password and password confirmation fields do not match"
}
]
}
分页
在服务器响应中应包含分页对象,格式如下:
currentPage
: 当前返回的页码totalPage
: 总页数totalRecord
: 总记录数limit
: 每页项数
示例:
{
"data": [
{
"id": 1
},
{
"id": 2
}
],
"pagination": {
"currentPage": 3,
"totalPage": 10,
"totalRecord": 92,
"limit": 10
}
}
版本
0.2.2
如何工作
该库提供了现成的接口来处理服务器响应,传递给参数的对象必须符合这些接口。
要初始化错误解析器,必须传递给构造函数:
errorMessages
: Map<String, E> - 键是错误代码,值是显示的消息defaultErrorMessage
: E - 未知错误的消息adapters
: Map<Type, ErrorMessageAdapter>fieldErrorMessages
: Map<String, Map<String, E>> - 键是字段名。值是一个类似于errorMessages
的表。
API解析器描述:
parse(ApiParserResponse<T> response)
- 返回ApiParserResponse
状态:成功、空或错误getParserResponse(ApiResponse<T> response)
- 解析服务器响应对象并返回处理结果getErrors(List<ErrorMessage> errors)
- 返回处理过的错误列表getMessageFromCode(String errorCode)
- 返回与此错误代码关联的消息getMessage(ErrorMessage errorMessage)
- 返回处理过的错误getFirstMessage(List<ErrorMessage> errors)
- 返回错误列表中的第一个处理过的错误getFieldMessageFromCode(String field, String errorCode)
- 返回错误列表中的第一个处理过的错误
Dart 示例
// 初始化api解析器
final apiParser = ApiParser(
adapters: {
ErrorMessageEntity: SimpleErrorMessageAdapter(),
},
errorMessages: {
ErrorCode.INVALID_LOGIN: Message.INVALID_LOGIN
},
fieldErrorMessages: {
FIELD.EMAIL: {
ErrorCode.INVALID_PASSWORD_CONFIRMATION: Message.PASSWORD_DO_NOT_MATCH,
},
FIELD.EMAIL_LENGTH: {ErrorCode.MIN: Message.EMAIL_LENGTH_MESSAGE}
},
defaultErrorMessage: Message.DEFAULT,
);
// 解析服务器响应
final ParserResponse<UserEntity> parserResponse = apiParser.getParserResponse(serverResponse);
// 使用解析器解析响应
final ApiParserResponse<UserEntity> apiParserResponse = apiParser.parse(serverResponse);
// 根据解析结果做相应的处理
switch (apiParserResponse.runtimeType) {
case ApiParserEmptyResponse: {
// 处理空响应的情况
break;
}
case ApiParserErrorResponse: {
// 处理错误响应的情况
break;
}
case ApiParserSuccessResponse: {
// 处理成功响应的情况
break;
}
}
更多关于Flutter错误解析插件api_error_parser的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复