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!
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
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With