Observables时出现错误时

Observables时出现错误时

本文介绍了使用Retrofit 2.0 Observables时出现错误时,如何获取Response主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在使用Retrofit 2.0进行返回Observable的api调用.当通话顺利并且响应如预期时,一切都很好.现在,我们有一个错误响应,它抛出一个onError.我想读取响应正文,即使它是一个错误.

I am using Retrofit 2.0 to make api calls that return Observables. It all works good when the call went through fine and the response is as expected. Now let's say we have an error response, it throws an onError. I would like to read the response body even when it is an Error.

示例

@FormUrlEncoded
@POST("tokenLogin")
Observable<LoginResponse> loginWithToken(
        @Field("token") String pin
);

当请求和响应有效时,我可以观察到正确的消息,并且在出现错误时按预期方式调用onError.

When the request and response are valid, I get the right observable and onError is being called as expected when there is an error.

正确的答案:

{ "status" : "authenticated" }

Observable将其转换为正确的Observable,我可以将响应读取为LoginResponse对象.

The Observable converts this into the right Observable and I can read the response as LoginResponse object.

现在,错误响应如下:

{ "errorMessage" : "You need to take some xyz action" }

我想阅读该错误响应并将消息显示给用户.我该怎么做?

I would like to read that error response and display the message to the user. How do I go about doing that?

推荐答案

只需检查throwable是否是HttpException的实例,然后就可以访问改造响应

Just check if the throwable is an instance of HttpException and then you can access the retrofit response

if (e instanceof HttpException) {
    ResponseBody body = ((HttpException) e).response().errorBody();
    ...
}

然后,您可以使用转换为反序列化(或自己完成).

Then you can use the converter to deserialize it (or do it yourself).

这篇关于使用Retrofit 2.0 Observables时出现错误时,如何获取Response主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:48