我想使用 Retorfit 2 实现错误处理机制。
可用的解决方案是使用我在当前存储库中找不到的 RetrofitError 类。
最佳答案
如果你是同步请求,你在接口(interface)中定义你的请求方法为Call<List<Car>>
.
执行请求后,您会收到响应和包装在 Response<T>
中的反序列化数据作为 Response<List<Car>>
.这种包装让您可以访问 header 、http 代码和原始响应正文。
您可以通过以下方式访问错误正文:
Call<List<Car>> carsCall = carInterface.loadCars();
try {
Response<List<Car>> carsResponse = carsCall.execute();
} catch (IOException e) {
e.printStackTrace();
//network Exception is throw here
}
if(carsResponse != null && !carsResponse.isSuccess() && carsReponse.errorBody() != null){
// handle carsResponse.errorBody()
}
对于异步调用,您会收到 Throwable
,如果网络调用过程中抛出I/O异常:
Call<List<Car>> call = service.loadCars();
call.enqueue(new Callback<List<Car>>() {
@Override
public void onResponse(Response<List<Car>> response) {
// Get result from response.body(), headers, status codes, etc
}
@Override
public void onFailure(Throwable t) {
//handle error
}
});
关于android - Retrofit 2 中的错误处理是如何进行的?我找不到大多数解决方案建议的 RetrofitError 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32517114/