问题
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