[英]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:
有几种方法可以解决这个问题:
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 自己产生的请求错误来纠正响应错误。ResponseSerializer
that knows how to decode success and failure values, which can you hook into Alamofire's response
method.ResponseSerializer
,它知道如何解码成功和失败值,您可以将其挂接到 Alamofire 的response
方法中。DataRequest
with a custom response
method that uses your custom serializer.response
方法扩展DataRequest
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.