android - Retrofit同步调用中的错误处理

标签 android retrofit

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

最佳答案

您的猜测似乎正确,使用同步调用 Retrofit 会抛出 RetrofitError代表错误:Reference .注意 handleError 中的 throw IllegalStateException 不应该在同步调用的情况下发生。

编辑: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;

其他引用:1

关于android - Retrofit同步调用中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30310796/

相关文章:

Android NDK UnsatisfiedLinkError - 一个令人惊讶的原因

android - 如何在 kotlin 中使用 Retrofit 解析 xml 响应?

java - 改造异步调用返回空对象

java - 不支持@DELETE方法(非body HTTP方法不能包含@Body或@TypedOutput。)

android - 有选择地将不记名 token 添加到 Retrofit 中的 header 中

android - 崩溃:android.widget.ListView.layoutChildren 中的 java.lang.IllegalStateException

android - Kotlin ArrayAdapter 错误 : None of the following functions can be called with the arguments supplied

android - 为什么我应该使用 View 参数而不是我想要的任何东西?

android - 如何在 21 级之前的设备中获取 R.attr.colorPrimary

java - 调试改造错误消息的最佳方法