API错误解析器
基于代码处理应用程序错误的库。
API响应说明
为了处理,错误必须符合以下标准: 服务器上的每个错误都应该遵循以下格式
- code:一个唯一的错误代码。用于识别错误。
- target:某种错误范围
- field - 与特定字段相关的错误
- common - 与整个请求相关的错误
- message(可选):开发者的错误消息(仅用于调试目的使用)
- source(可选):用于存储附加数据的容器。任意结构:(field:资源对象的属性名称。如果将target设置为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": {
"field": "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"
}
]
}
版本
0.0.3
工作原理
该库提供了一套源对象来解析服务器响应。所有提供的对象都实现了Mappable
接口。
单独解析 JSON
也是可能的,并返回已处理的结果。对于使用 ObjectMapper 库进行解析,请访问 ObjectMapper
要初始化 ErrorParser,您必须传递给构造函数
errorMessages: Dictionary<String, String>
- 键是错误代码,值是显示的消息defaultErrorMessage: String
- 未知错误的短信
API 解析器说明
parse(json: [String: Any])
- 解析JSON
并返回处理结果parse(response: ApiResponseEntity<T>)
- 解析服务器响应对象并返回处理结果getErrors(errors: Array<ErrorMessageEntity>)
- 返回处理后的错误列表getMessage(errorCode: String)
- 返回与该错误代码关联的消息getMessage(errorMessage: ErrorMessageEntity)
- 返回处理后的错误getFirstMessage(errors: Array<ErrorMessageEntity>)
- 返回列表中的第一个处理后的错误
安装
您希望将 pod 'ApiErrorParser', '~> version'
类似以下内容添加到 Podfile 中
target 'MyApp' do
pod 'ApiErrorParser', '~> version'
end
然后在终端中运行 pod install
或从 CocoaPods.app
运行。
许可
ApiErrorParser 采用 MIT 许可发布。有关详细信息,请参阅 LICENSE。