iZBasit
iZBasit

Reputation: 1313

How to handle network errors in Retrofit 2 with RxJava

I am using Retrofit2 with RxJava. So my call looks something like

subscriptions.add(authenticateUser(mReq, refreshRequest)
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .subscribe(authResponseModel -> {
                    processResponse(authResponseModel, userName, encryptedPass);
                }, throwable ->
                {
                    LOGW(TAG, throwable.getMessage());
                }));

It's an authentication api. So when the api call fails, I get a response from the server like

{"messages":["Invalid username or password "]}

along with 400 Bad Request

I get 400 Bad Request in the throwable object as expected. But I want to receive the message thrown by the server. I am unable to figure out how to go about doing it. Can someone help out.

Upvotes: 2

Views: 9346

Answers (1)

LordRaydenMK
LordRaydenMK

Reputation: 13321

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());
}

Assuming you are using Gson:

public class Error {
    public List<String> messages;
}

the content of messages should be a list of error messages. In your example messages.get(0) would be: Invalid username or password

Upvotes: 4

Related Questions