如何使用 RxJava 处理 Retrofit 2 中的网络错误
How to handle network errors in Retrofit 2 with RxJava
我正在使用 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
的内容应该是错误信息列表。在你的例子中
messages.get(0)
将是:无效的用户名或密码
我正在使用 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
的内容应该是错误信息列表。在你的例子中
messages.get(0)
将是:无效的用户名或密码