我使用基本的Call
对象调用api:
public interface dataApi {
@GET("animal/cats")
Call<AllAnimals> getAllData(
@Query("api_key") String apiKey
);
}
这样我就可以在 View 模型中获得响应:
call.enqueue(new Callback<AllAnimals>() {
@Override
public void onResponse(Call<AllAnimals> call, Response<AllAnimals> response) {
animals.setValue(response.body());
}
@Override
public void onFailure(Call<AllAnimals> call, Throwable t) {
Log.i(TAG, "onFailure: " + t);
}
});
这里没什么特别的。
我有这种方法的几个问题
FIRST -例如,如果我输入了错误的api键,则响应应该给我一个包含问题代码的响应,而我得到的是空主体。
第二个我计划进行更多的api调用,这是一个巨大的代码重复,可以处理我编写的每个调用的错误。
如何针对这种情况实现自定义错误处理,这也将适用于其他调用?
最佳答案
我认为您可以使用okhttp interceptor并定义自己的ResponseBody转换器来解决您的问题。
定义一个简单的拦截器
Interceptor interceptor = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String url = request.url().toString();
System.out.println(request.url());
okhttp3.Response response = chain.proceed(request);
if (!response.isSuccessful() && url.contains("animal/cats")) {
// request failed begin to modify response body
response = response.newBuilder()
.body(ResponseBody.create(MediaType.parse("application/json"), new byte[] {}))
.build();
}
return response;
}
};
定义自我ResponseBody转换器
com.squareup.retrofit2:converter-jackson中的大多数代码我们只添加两行:
final class JacksonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final ObjectReader adapter;
JacksonResponseBodyConverter(ObjectReader adapter) {
this.adapter = adapter;
}
@Override public T convert(ResponseBody value) throws IOException {
try {
if (value.contentLength() == 0) {
return null;
}
return adapter.readValue(value.charStream());
} finally {
value.close();
}
}
}
添加以下代码:
if (value.contentLength() == 0) {
return null;
}
关于java - 如何使用Retroift2实现自定义错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61955471/