Retrofit2结果拦截器和判断异常类型

结果拦截器

Interceptor responseInterceptor = new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        if (response.body() != null) {
            String json = response.body().string().replace("\"data\":null", "\"data\":{}");
            ResponseBody body = ResponseBody.create(response.body().contentType(), json);
            return response.newBuilder().body(body).build();
        }
        return response;
    }
};

判断异常类型

@Override
public void accept(Throwable throwable) throws Exception {
    if (throwable instanceof HttpException) {
        String json = ((HttpException) throwable).response().errorBody().string();
    }
}

发表评论