如何从MoyaError获取错误响应

编程入门 行业动态 更新时间:2024-10-25 17:29:25
本文介绍了如何从MoyaError获取错误响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

类似于 this ,但这一次我需要检索服务器的JSOn响应.

similar to this but this time i need to retrieve the JSOn response of the server.

这是我现有的代码:

return Observable.create{ observer in let _ = self.provider .request(.getMerchantDetails(qrId: qrId)) .filterSuccessfulStatusCodes() .mapJSON() .subscribe(onNext: { response in observer.onNext(RQRMerchant(json: JSON(response))) }, onError: { error in observer.onError(error) }) return Disposables.create()

我的问题是:我可以通过error.localizedDescription获取错误响应代码404,但我也想获取404 HTTP请求的JSON响应.

my question is: I can get the error response code 404 by error.localizedDescription But I also want to get the JSON response of the 404 HTTP request.

推荐答案

我也遇到了同样的问题,对我来说,最简单,最干净的解决方案是扩展MoyaError,以包括已解码错误对象的属性. .在我的情况下,我使用的是Decodable对象,因此您可以为可解码的BackendError编写类似的代码,以表示可能从服务器获取的错误:

I've been faced with the same problem, and for me the easiest and cleanest solution was to extend MoyaError to include a property for the decoded error object. In my case I'm using Decodable objects, so you could write something like this for a decodable BackendError representing the error you may get from your server:

extension MoyaError { public var backendError: BackendError? { return response.flatMap { try? $0.map(BackendError.self) } } }

如果您更喜欢直接处理JSON,则可以调用mapJSON方法,而不是映射到Decodable.

If you instead prefer to directly deal with JSON you can invoke the mapJSONmethod instead of mapping to a Decodable.

然后,您只需要执行以下操作即可获取不成功的状态代码的错误信息:

Then you just have to do the following to get the error information for non successful status codes:

onError: { error in let backendError = (error as? MoyaError).backendError }

更多推荐

如何从MoyaError获取错误响应

本文发布于:2023-11-26 15:20:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634251.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   MoyaError

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!