简体   繁体   中英

Custom error handling CallAdapter for Retofit2 + RxJava2

Server sends response in case of success (code 2xx):

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

And in case of fail (4xx) the following Json is sent inside errorBody :

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

I am using Retrofit v2.4.0 and RxJava2.

How can I create custom CallAdapter for my case? I have read Square's ErrorHandlingAdapter but it was without 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:

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. I hope this is the answer that you are finding.

you can remove statusCode, message if no in response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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