How to handle network errors in Retrofit 2 with RxJava

南笙酒味 提交于 2019-11-30 19:30:18

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/35987037/how-to-handle-network-errors-in-retrofit-2-with-rxjava

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!