我正在使用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;
}