20.5 C
Bangalore
December 17, 2018
Untitled

Error handling when using RxJava2 & Retrofit2

android

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:


@GET("search/users")

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

We make the request as follows:

APIService.getUserDetails(1324)

    .subscribeOn(Schedulers.io())

    .observeOn(AndroidSchedulers.mainThread())

    .subscribe(new SingleObserver<User>() {

    @Override

    public void onSubscribe(Disposable disposable) {

    }


    @Override

    public void onSuccess(User user) {

        //handle success response.

    }

    @Override

    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().


@Override 
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.