How to get error statusCode from `MoyaError`?

≯℡__Kan透↙ 提交于 2020-01-03 21:09:13

问题


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
    }
}

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(Status Code: 409, Data Length: 0)

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.

Thanks!


回答1:


Migrating from the comment

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

First case the error as as MoyaError

let moyaError: MoyaError? = error as? 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


来源:https://stackoverflow.com/questions/41911565/how-to-get-error-statuscode-from-moyaerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!