如何从`MoyaError`获取错误statusCode? [英] How to get error statusCode from `MoyaError`?

查看:975
本文介绍了如何从`MoyaError`获取错误statusCode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Moya Moya_ModelMapper RxSwift 执行网络请求。
这是我的示例代码:

I'm using a Moya, Moya_ModelMapper and RxSwift to perform network requests. Here is my example code:

let provider = RxMoyaProvider<MyEndpoint>()
let observable: Observable<RegistrationResponse> = provider.request(.register(firstName: "", lastName: "", email: "", password: "")).mapObject(type: RegistrationResponse.self)
observable.subscribe {
    [weak self] (event: Event<RegistrationResponse>) in
    switch event {
    case .next(let response):
        print(response)
    case .error(let error):
        print(error)
    case .completed:
        break
    }
}

一切正常,但是当我收到 409 状态代码时,我不知道如何获取错误代码服务器的响应类型。
如果我打印错误,我将得到:

Everything works fine, but I don't know how to get an error code when I receive for example a 409 status code response type from the server. If I print the error I will get:

jsonMapping(状态代码:409,数据长度:0)

但我不知道如何通过代码获取此状态代码。错误是 MoyaError ,这是一种枚举类型。这是MoyaError的源代码

but I don't know how to get this status code by code. The error is MoyaError which is an Enum type. Here it's a source code of MoyaError.

谢谢!

推荐答案

从评论中迁移

Moya错误不直接包含错误代码,而是包含MoyaResponses,后者又包含错误代码。

A Moya error does not contain an error code directly, they do contain MoyaResponses which do in turn contain the error code.

第一种情况错误如MoyaError

First case the error as as MoyaError

let moyaError: MoyaError? = error as? MoyaError

可选的MoyaError将包含可选的响应,使用可选的链接,我们得到:

The optional MoyaError will contain an optional response, using optional chaining we get:

let response : Response? = moyaError?.response

最后我们可以获得响应的状态码。

Lastly we can get the response its status code.

let statusCode : int? = response?.statusCode

这篇关于如何从`MoyaError`获取错误statusCode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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