Moya: Question: How to get the response body of an error?

Moya 8.0.0

func getPersonDetails(personID: String) -> Observable<Person>? {
return Observable.create{ observer in
            let _ = self.provider
                .request(.getPersonDetails(personID: personID))
                .filterSuccessfulStatusCodes()
                .mapJSON()
                .subscribe(onNext: { response in
                    observer.onNext(Person(json: JSON(response)))
                }, onError: { error in
                    print(error.localizedDescription)
                    observer.onError(error)
                })
            return Disposables.create()
            }
        }
}

assuming the api will return an error and I can retrieve the error code, how can i retrieve the response json payload?

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 1
  • Comments: 16 (9 by maintainers)

Most upvoted comments

Hey @ledikari. @pedrovereza is right, in 9.0.0 the underlying case would be getting response as well, but right now you can just cast error to Moya.Error and parse the response data:

.catchError { error in
    if let error = error as? Moya.Error, body = error.response?.mapJSON() {}
}

the syntax might be off since I’m writing this from the bus, but the idea should be alright. 😅

Let us know if it helped!

@sunshinejr tried your code, but errorResponse.response is nil

do {
     let errorResponse = error as? Moya.MoyaError
     if let body = try errorResponse?.response?.mapJSON(){
          print(body)
     }
} catch {
     print(error)
}

@ledikari Not sure, we are tracking progress in #1075, but slowly getting there. I didn’t recommend using our 9.0.0-dev since there might be some breaking changes in the near future, so please use it at your own risk 👍