【问题标题】:How to parse error when api request fails using responsedecodable in swift alamofireapi请求失败时如何在swift alamofire中使用responsedecodable解析错误
【发布时间】:2020-07-06 15:52:58
【问题描述】:

我正在尝试使用 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 错误?或者如果请求失败,也许可以解析另一个对象?还是有其他方法可以访问错误消息?

【问题讨论】:

  • 当它“失败”时,你会得到一个不同的 JSON 类型的 200,还是你有不同的 HTTP 代码?那么这取决于您是否需要处理成功或失败的案例。
  • @Larme 失败时,我得到 400 和 JSON 错误。当它成功时 200 和 JSON for UserConfig
  • 您可以使用自定义validate() stackoverflow.com/questions/45955823/…(在以前的版本中,但在较新的版本中应该仍然可用)。然后你决定做什么:如果解析的错误不为零,则调用成功,如果不是,则不失败?此外,您应该能够从AFError 检索数据。或者只是访问result.data
  • AFError 将不包含响应 Data。您可以创建自己的错误以包含已解析的错误响应。
  • @JonShier 是的,这就是我需要的,也许您有更多信息如何做到这一点?

标签: swift alamofire


【解决方案1】:

在 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))
}

然后,在您的响应处理程序中,您需要从AFErrorunderlyingError 属性转换为您的自定义错误类型:

.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.
}
  1. 使用Decodable 容器类型将您的响应解析为您期望的类型或错误表示。您应该可以在其他地方找到示例,但在 Alamofire 方面,它会像这样工作:
.responseDecodable(of: ContainerType<SomeType>.self) { response in
    // Do something with response.
}
  1. 编写自定义的ResponseSerializer 类型,用于检查响应并在检测到故障时解析错误类型,否则解析预期类型。我们在our documentation 中有示例。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 2017-10-29
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多