【发布时间】:2014-07-15 23:51:17
【问题描述】:
我将 Retrofit 用于异步和同步 api 调用。
对于这两者,我定义了一个自定义错误处理程序来处理未经授权的响应。对于同步调用,我在接口方法上声明了自定义异常,我用 try/catch 包围了接口实现,它工作得很好。我可以捕获未经授权的异常。
我对使用回调的异步调用进行了同样的尝试,但效果不一样。我必须在回调的失败方法中处理它,而不是在 try/catch 中捕获异常。
接口方法如下:
@GET("getGardenGnomes")
void getGardenGnomes(@Header("Authorisation") String authorisation, Callback<GardenGnomes> callback) throws UnauthorisedException;
这里是实现:
void onClick() {
try {
getGardenGnomes()
} catch (UnauthorisedException exception) {
// .... handle the exception ....
}
}
void getGardenGnomes() throws UnauthorisedException {
// .... get client etc etc ....
client.getGardenGnomes(authorisation, new Callback<GardenGnomes>() {
@Override
public void success(GardenGnomes gardenGnomes, Response response) {
// .... do something ....
}
@Override
public void failure(RetrofitError error) {
// .... handle error ....
}
}
);
}
问题是:
是不是应该只处理Callback的failure(RetrofitError)方法中的异常,不要在异步调用的接口方法上声明throws UnauthorisedException?
或者最好的实现方式是什么?
【问题讨论】: