当api请求失败时如何在swift alamofire中使用responsedecodable解析错误

AsM*_*nas 4 swift alamofire

我正在尝试使用 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)
        }
    }
Run Code Online (Sandbox Code Playgroud)

当调用成功时,它成功地将 JSON 解析为模型。但是,在某些特殊情况下,它会失败。例如,如果用户已经注册,我会收到 JSON 响应:

{
   "error":{
      "message":"User already exist"
   }
}
Run Code Online (Sandbox Code Playgroud)

是否可以覆盖我们收到的 AF 错误?或者如果请求失败,也许可以解析另一个对象?或者还有其他方法可以访问错误消息吗?

Jon*_*ier 9

在 Alamofire 中有多种方法可以解决这个问题。

  1. validate()采用闭包的方法中,解析错误主体并生成.failure带有自定义关联错误的结果:
.validate { request, response, data
    // Check request or response state, parse data into a custom Error type.
    return .failure(MyCustomErrorType.case(parsedError))
}
Run Code Online (Sandbox Code Playgroud)

然后,在响应处理程序中,您需要从 的 属性转换为自定义错误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.
}
Run Code Online (Sandbox Code Playgroud)
  1. 使用Decodable容器类型将您的响应解析为您期望的类型或错误表示形式。您应该能够在其他地方找到示例,但在 Alamofire 方面,它的工作原理如下:
.responseDecodable(of: ContainerType<SomeType>.self) { response in
    // Do something with response.
}
Run Code Online (Sandbox Code Playgroud)
  1. 编写一个自定义ResponseSerializer类型,用于在检测到故障时检查响应并解析错误类型,否则解析预期类型。我们的文档中有示例。

在这些选项中,我通常使用包装器类型,除非我已经使用自己的自定义Error类型,在这种情况下,验证器相当简单。自定义序列化器是最繁重的工作,但也为您提供了最大的灵活性,特别是如果您需要自定义响应处理的其他方面。