Retrofit2 is a nice library for making HTTP rest requests. It includes a static utility (CallUtils) for getting the result from your request, but if the api you’re calling doesn’t return a 2xx request it will throw an HttpException. Here is an example of using that CallUtils method.
Call<SomekindOfObject> call = .....; return CallUtils.getResult(call);
The problem is when there is an error that HttpException does not return the message body, and oftentimes that body has information about why your request failed. To fix this problem I created a static method that captures the body and response code to return the body as part of the exception.
public static <T> T getResult(retrofit2.Call<T> call) throws MyCustomException { if (call != null) { try { Response<T> response = call.execute(); if (response.isSuccessful()) { return response.body(); } else { String errorMessage = response.errorBody() != null ? response.errorBody().string() : ""; throw new MyCustomException(response.code(), errorMessage); } } catch (IOException ioe) { throw new MyCustomException(400, "error executing call"); } } return null; }
The post Retrofit2: Get the body from an error response first appeared on Object Partners.