20.5 C
December 17, 2018

Error handling when using RxJava2 & Retrofit2


I have been using combination of RxJava and Retrofit for a while now to make REST API calls. Here I am going to talk only about how to parse error responses.

Assume we have a request as below:


Single<User> getUserDetails(@Query("id") int id);

We make the request as follows:




    .subscribe(new SingleObserver<User>() {


    public void onSubscribe(Disposable disposable) {



    public void onSuccess(User user) {

        //handle success response.



    public void onError(Throwable throwable) {

        //handle error.



Assume for some reason server returned error, probably because the user does not exist. Error returned by server will be present in throwable object.

Inorder to parse the error we need to know the error json structure before hand. Every implementation of error structure in server side differs, but for the time being lets assume structure is as follows:


    "status": "BAD_REQUEST",

    "code": "002",

    "description": “User ID not found"


Create a POJO class which matches the above structure, ErrorResponse.class.

Create a utility method which parses the json string from throwable object to Error POJO which we just created. I am using Gson to convert json string to POJO.

public static ErrorResponse parseError(Throwable throwable) {

    if (throwable instanceof HttpException) {

        HttpException exception = (HttpException) throwable;

        try {

            String jsonString = exception.response().errorBody().string();

            Gson gson = new Gson();

            return gson.fromJson(jsonString, ErrorResponse.class);

        } catch (IOException e) {

            Log.e("API Error", e.getMessage());

            return new ErrorResponse(e.getMessage());



    return new ErrorResponse("Unknown Error”);


This utility method can be called from onError() of SingleObserver().

public void onError(Throwable throwable) { 
    ErrorResponse error = Utils.parseError(throwable); 
    //Send this error object back to UI for display.

Related posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.