我正在使用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)将是:无效的用户名或密码
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。