Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get Response body when there is an error when using Retrofit 2.0 Observables

I am using Retrofit 2.0 to make api calls that return Observables. It all works good when the call went through fine and the response is as expected. Now let's say we have an error response, it throws an onError. I would like to read the response body even when it is an Error.

Example

@FormUrlEncoded @POST("tokenLogin") Observable<LoginResponse> loginWithToken(         @Field("token") String pin ); 

When the request and response are valid, I get the right observable and onError is being called as expected when there is an error.

Correct Response:

{ "status" : "authenticated" } 

The Observable converts this into the right Observable and I can read the response as LoginResponse object.

Now, the Error Response is as follows:

{ "errorMessage" : "You need to take some xyz action" } 

I would like to read that error response and display the message to the user. How do I go about doing that?

like image 631
achie Avatar asked Nov 19 '15 22:11

achie


People also ask

How do I get error message from retrofit response?

you can simply use "response. message(). toString()" which will give the same error string in a more readable format.

How do I send a body in post request in retrofit?

Request Body@POST("users/new") Call<User> createUser(@Body User user); The object will also be converted using a converter specified on the Retrofit instance. If no converter is added, only RequestBody can be used.

How do you use RxJava with retrofit?

To use RxJava in retrofit environment we need to do just two major changes: Add the RxJava in Retrofit Builder. Use Observable type in the interface instead of Call.


1 Answers

Just check if the throwable is an instance of HttpException and then you can access the retrofit response

if (e instanceof HttpException) {     ResponseBody body = ((HttpException) e).response().errorBody();     ... } 

Then you can use the converter to deserialize it (or do it yourself).

like image 149
Tim C Avatar answered Oct 04 '22 15:10

Tim C