我正在尝试使用 alamofire 和 responseDecodable 向后端发出 API 请求。
AF.request(Router.registerFacebookUser(facebookToken: token)).validate().responseDecodable(of: UserConfig.self) { result in
switch result.result {
case let .success(userConfig):
onAuthentication(userConfig)
case let .failure(error):
print(error)
//somehow get the message from ERROR JSON and pass it here
onFailure(error.localizedDescription)
}
}
当调用成功时,成功将JSON解析为模型。但是,在某些特殊情况下,它应该会失败。例如,如果用户已经注册,我会收到一个响应 JSON:
{
"error":{
"message":"User already exist"
}
}
是否可以覆盖我们收到的 AF 错误?或者,如果请求失败,也许可以解析另一个对象?还是有其他方法可以访问错误消息?
最佳答案
在 Alamofire 中有几种方法可以解决这个问题。
- 在采用闭包的
validate()
方法中,解析错误主体并生成带有自定义关联错误的.failure
结果:
.validate { request, response, data
// Check request or response state, parse data into a custom Error type.
return .failure(MyCustomErrorType.case(parsedError))
}
然后,在您的响应处理程序中,您需要将 AFError
的 underlyingError
属性转换为您的自定义错误类型:
.responseDecodable(of: SomeType.self) { response in
switch response.result {
case let .success(value): // Do something.
case let .failure(error):
let customError = error.underlyingError as? MyCustomErrorType
// Do something with the error, like extracting the associated value.
}
- 使用
Decodable
容器类型将您的响应解析为您期望的类型或错误表示。您应该能够在其他地方找到示例,但在 Alamofire 方面,它的工作方式如下:
.responseDecodable(of: ContainerType<SomeType>.self) { response in
// Do something with response.
}
- 编写一个自定义的
ResponseSerializer
类型,用于检查响应并在检测到故障时解析错误类型,否则解析预期类型。我们在 our documentation 中有示例.
在这些选项中,我通常使用包装器类型,除非我已经在使用我自己的自定义 Error
类型,在这种情况下验证器相当简单。自定义序列化程序工作量最大,但也为您提供最大的灵 active ,尤其是在您需要自定义响应处理的其他方面时。
关于swift - 如何在 api 请求失败时使用 swift alamofire 中的 responsedecodable 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62759759/