我用基本的改造Call
对象调用 api:
public interface dataApi {
@GET("animal/cats")
Call<AllAnimals> getAllData(
@Query("api_key") String apiKey
);
}
我可以像这样在我的视图模型中得到响应:
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);
}
});
这里没有什么特别的。
我对这种方法有几个问题
首先- 例如,如果我提供了错误的 api 密钥,则响应应该给我一个带有问题代码的响应,而不是我只得到 null 正文。
第二,我计划进行更多的 api 调用,每次我写的调用都需要处理大量的代码重复。
如何针对这种情况实施自定义错误处理,这也将适用于其他调用?