如何从MoyaError获取错误响应 [英] how to get the error response from MoyaError

查看:823
本文介绍了如何从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获取错误响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆