android – 如何使用RxJava处理Retrofit 2中的网络错误

我正在使用Retrofit2和RxJava.所以我的电话看起来像

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

这是一个身份验证API.因此,当api调用失败时,我从服务器得到响应

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

以及400 Bad Request

我按预期在throwable对象中得到400 Bad Request.但我想收到服务器抛出的消息.我无法弄清楚如何去做.
有人可以帮忙吗?

解决方法:

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

假设您正在使用Gson:

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

消息的内容应该是错误消息的列表.在你的例子中
messages.get(0)将是:无效的用户名或密码

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...