Retrofit在同步调用中处理错误

Fei*_* Qu 19 android retrofit

我试图找出在Retrofit同步调用中进行错误处理的正确方法.我知道对于异步调用,Retrofit有一个针对失败案例的回调.但是我应该如何处理同步调用的错误?我的猜测是用try块包装调用并处理catch块中的RetrofitError异常.

Bhu*_*tik 6

您的猜测似乎是正确的,使用同步调用Retrofit会抛出表示错误的RetrofitError:Reference.请注意, throw IllegalStateExceptionhandleError同步调用的情况下不应发生in.

编辑:似乎Retrofit正在慢慢转向2.0版本,如果您计划使用Retrofit 2.0,我建议您阅读文档以了解它是如何在新版本中完成的.

编辑pt2: Retrofit已经转移到2.0版本,现在如果你想处理错误,你不再需要捕获RetrofitErrors而是IOException.你可以直接看一下execute()的实现

/**
 * Synchronously send the request and return its response.
 *
 * @throws IOException if a problem occurred talking to the server.
 * @throws RuntimeException (and subclasses) if an unexpected error occurs creating the request
 * or decoding the response.
 */
Response<T> execute() throws IOException;
Run Code Online (Sandbox Code Playgroud)

其他参考文献:1