Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get error statusCode from `MoyaError`?

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!

like image 986
kamwysoc Avatar asked Jan 28 '17 15:01

kamwysoc


2 Answers

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
like image 146
milo526 Avatar answered Oct 04 '22 17:10

milo526


For the ones who had a nil moyaError.response, here is a way to get the errorCode

 if let error = ((error as? MoyaError)?.errorUserInfo["NSUnderlyingError"] as? Alamofire.AFError)?.underlyingError as? NSError, error.domain == NSURLErrorDomain, error.code == NSURLErrorNotConnectedToInternet || error.code == NSURLErrorTimedOut || error.code == NSURLErrorNetworkConnectionLost {
                   print("not connected")
      }
like image 44
Niib Fouda Avatar answered Oct 04 '22 16:10

Niib Fouda