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

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


You can add this code block to display the error message.

@Override
public void onFailure(Throwable t) {

 if (t instanceof HttpException) {
        ResponseBody body = ((HttpException) t).response().errorBody();
        Gson gson = new Gson();
        TypeAdapter<ErrorParser> adapter = gson.getAdapter
                (ErrorParser
                        .class);
        try {
            ErrorParser errorParser =
                    adapter.fromJson(body.string());

            Logger.i(TAG, "Error:" + errorParser.getError());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}