当服务器返回错误时,使用Immutables进行改造会引发运行时异常

时间:2016-05-21 11:27:15

标签: java json immutability retrofit2

如果响应成功,一切正常,但是当我从服务器收到101错误时,会抛出一个运行时异常:“无法调用public ... TestResponse()没有args”,问题很明显json无法反序列化,但是当我收到错误响应时,如何使用错误对象而不是“TestResponse”?

改造界面:

@Headers("Accept: application/json")
@POST("api")
Observable<TestResponse> test();

响应对象:

@Value.Immutable()
@Gson.TypeAdapters
public abstract class TestResponse {
    public abstract String success();
}

成功回应json:

{"success" : "response successful"}

响应错误json:

[{"error":{"type":101,"description":"not authorized"}}]

1 个答案:

答案 0 :(得分:1)

You will have to extend the retrofit Callback Class and write your custom Callback for error handling. In your custom Callback class you can deserialize the errorBody into any object type you want. This tutorial has a nice explanation on how to do error handling using that.