How to handle network errors in Retrofit 2 with RxJava

泪湿孤枕 提交于 2019-12-01 01:01:30
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

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