简体   繁体   English

Alamofire 5 响应可解码失败

[英]Alamofire 5 responseDecodable failure

Alamofire has a nifty .responseDecodable function that makes parsing simple when request.result =.success but, how to decode an error object in case of failure ? Alamofire 有一个漂亮的.responseDecodable function 可以在request.result =.success时简化解析,但是,如何在failure的情况下解码错误 object ?

In my case, backend can return a myriad of errors since, for instance, a credit card charge may have an infinitude of reasons - OTP failed, declined etc.就我而言,后端可能会返回无数错误,例如,信用卡费用可能有无数原因 - OTP 失败、拒绝等。

Should i change my approach towards requests?我应该改变我对请求的处理方式吗? Since Alamofire doesn't really support error handling (at least with responseDecodable ) as it stands.由于 Alamofire 并不真正支持错误处理(至少使用responseDecodable )。

As I understood response.result should be enum with 2 states: success(value) & failure(Error).据我了解, response.result应该是具有 2 个状态的enum :成功(值)和失败(错误)。 You need to switch between them:您需要在它们之间切换:

 switch response.result {
case .success(let value): print(value)
case .failure(let error): print(error)
}

This depends entirely on how your responses are structured.这完全取决于您的回复的结构。 There are a few ways to approach this:有几种方法可以解决这个问题:

  • Create an enum representing your responses, generic to the success (and perhaps failure) value.创建一个表示您的响应的enum ,通用成功(可能还有失败)值。 Something like APIResponse<Success> , which is itself Decodable and will try to parse the success value or an error from the response.类似Decodable APIResponse<Success>的东西,它本身就是可解码的,并且会尝试从响应中解析成功值或错误。 This would allow you to keep using responseDecodable but you'll have to rectify response errors with request errors produced by Alamofire yourself.这将允许您继续使用responseDecodable ,但您必须使用 Alamofire 自己产生的请求错误来纠正响应错误。
  • Create your own ResponseSerializer that knows how to decode success and failure values, which can you hook into Alamofire's response method.创建您自己的ResponseSerializer ,它知道如何解码成功和失败值,您可以将其挂接到 Alamofire 的response方法中。
  • Relatedly, you can extend DataRequest with a custom response method that uses your custom serializer.相关地,您可以使用自定义序列化程序的自定义response方法扩展DataRequest

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM