简体   繁体   English

自定义错误处理CallAdapter for Retofit2 + RxJava2

[英]Custom error handling CallAdapter for Retofit2 + RxJava2

Server sends response in case of success (code 2xx): 服务器成功发送响应(代码2xx):

{
    "user":"User",
    "age":16
}

And in case of fail (4xx) the following Json is sent inside errorBody : 并且如果失败(4xx), 则会在errorBody内部发送以下Json:

{
    "errorMessage":"Server is not working",
    "action":{
         ...
    }
}

I am using Retrofit v2.4.0 and RxJava2. 我正在使用Retrofit v2.4.0和RxJava2。

How can I create custom CallAdapter for my case? 如何为我的案例创建自定义CallAdapter I have read Square's ErrorHandlingAdapter but it was without RxJava2 我已经阅读了Square的ErrorHandlingAdapter,但是它没有RxJava2

it is highly recommended using same object because of enque of retrofit, you can do this using generic model 强烈建议您使用同一对象,因为可能会进行改造,您可以使用通用模型来执行此操作

public class GenericResponseModel {
    public int statusCode;
    public String message;
    public Object data;
}

and then parse into a particular model in your onNetworkSuccess and onNetworkError something like this: 然后解析为onNetworkSuccess和onNetworkError中的特定模型,如下所示:

HomeModel homeModel = new Gson().fromJson(new Gson().toJson(genericResponseModel.data), HomeModel[].class);

using this approach you can make BaseModel and can treat with different responses too. 使用这种方法,您可以制作BaseModel,也可以处理不同的响应。 I hope this is the answer that you are finding. 我希望这是您找到的答案。

you can remove statusCode, message if no in response 您可以删除statusCode,如果没有响应则显示消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM