Retrofit 在同步调用中的错误处理
Error handling in synchronous call by Retrofit
我正在尝试找出在 Retrofit 同步调用中进行错误处理的正确方法。我知道对于异步调用,Retrofit 有一个失败案例的回调。但是我应该如何处理同步调用的错误?我的猜测是用 try 块包装调用并在 catch 块中处理 RetrofitError 异常。
很难找到这个。没有人真正谈论同步调用的错误处理。但我发现了一些东西。我不完全确定是否应该添加下一行(对于自定义错误肯定应该添加,但事实并非如此)我找到了 here
Foo doFoo() throws RetroFitError;
同步调用应该发生在这样的 try catch 子句中:
try{
doFoo();
}catch(RetroFitError e){
}
找到here
你的猜测似乎是正确的,使用同步调用 Retrofit 是为了抛出一个 RetrofitError representing the error: Reference。请注意,在同步调用的情况下,handleError
中的 throw IllegalStateException
不应发生。
编辑: 看来 Retrofit 正在慢慢向 2.0 版本推进,如果您打算使用 Retrofit 2.0,我建议您阅读文档以了解它是如何在新版本。
Edit 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;
其他参考文献:1
我正在尝试找出在 Retrofit 同步调用中进行错误处理的正确方法。我知道对于异步调用,Retrofit 有一个失败案例的回调。但是我应该如何处理同步调用的错误?我的猜测是用 try 块包装调用并在 catch 块中处理 RetrofitError 异常。
很难找到这个。没有人真正谈论同步调用的错误处理。但我发现了一些东西。我不完全确定是否应该添加下一行(对于自定义错误肯定应该添加,但事实并非如此)我找到了 here
Foo doFoo() throws RetroFitError;
同步调用应该发生在这样的 try catch 子句中:
try{
doFoo();
}catch(RetroFitError e){
}
找到here
你的猜测似乎是正确的,使用同步调用 Retrofit 是为了抛出一个 RetrofitError representing the error: Reference。请注意,在同步调用的情况下,handleError
中的 throw IllegalStateException
不应发生。
编辑: 看来 Retrofit 正在慢慢向 2.0 版本推进,如果您打算使用 Retrofit 2.0,我建议您阅读文档以了解它是如何在新版本。
Edit 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;
其他参考文献:1