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. } 
Tags : androidjava
Jacks Varghese
Over 7+ Years of Experience in Design and development in embedded and Mobile application. Expertise and Executed multiple Android SDK applications for STB (Set Top Box), Google TV, and Mobile Devices.

Leave a Reply

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