I assume you are defining your call as:
Observable<YourModel> doStuff();
You get a onSuccess
callback for HTTP codes 200-300 and onError
for HTTP error codes, network errors, parsing errors...
You can also define your call as:
Observable<Response<YourModel>> doStuff();
and you will get a call to onSuccess
when there is a HTTP error.
In onSuccess
you need to check response.isSuccess()
. It returns true for 200-300 status codes and you can access the response body with response.body()
If response.isSuccess()
returns false you can convert the error body to your model class using:
if(throwable instanceof HttpException) {
//we have a HTTP exception (HTTP status code is not 200-300)
Converter<ResponseBody, Error> errorConverter =
retrofit.responseBodyConverter(Error.class, new Annotation[0]);
//maybe check if ((HttpException) throwable).code() == 400 ??
Error error = errorConverter.convert(((HttpException) throwable).response().errorBody());
}