Android 如何处理RxJava改造2中的网络错误
我正在使用RxJava的改型2。所以我的电话看起来像Android 如何处理RxJava改造2中的网络错误,android,rx-java,retrofit2,Android,Rx Java,Retrofit2,我正在使用RxJava的改型2。所以我的电话看起来像 subscriptions.add(authenticateUser(mReq, refreshRequest) .observeOn(Schedulers.io()) .subscribeOn(Schedulers.io()) .subscribe(authResponseModel -> { pro
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错误请求
我在throwable
对象中获得了400个错误请求。但是我想接收服务器抛出的消息。我不知道如何着手做这件事。
有人能帮忙吗。if(HttpException的可丢弃实例){
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());
}
//我们有一个HTTP异常(HTTP状态代码不是200-300)
转换器错误转换器=
改装.responseBodyConverter(Error.class,新注释[0]);
//可能会检查((HttpException)throwable.code()==400??
Error Error=errorConverter.convert(((HttpException)throwable.response().errorBody());
}
假设您正在使用Gson:
public class Error {
public List<String> messages;
}
公共类错误{
公开列表信息;
}
消息的内容应为错误消息列表。在你的例子中
消息。获取(0)
将是:无效的用户名或密码。throwable只给出了400个错误的请求。是否检查了((HttpException)e).response().errorBody()
?((HttpException)e).response()
返回响应对象。这里有响应的真实主体,response.body()
——通常用于http 200——以及错误主体,在出现错误时应该填充。检查两者的内容。看一看改型的代码库。它使用了一个转换器
,该转换器将错误主体映射到一个java对象;你能解释一下这个“改装”对象吗?它是改装实例(来自改装2)