【问题标题】:Error handling in synchronous call by RetrofitRetrofit同步调用中的错误处理
【发布时间】:2015-07-30 09:44:27
【问题描述】:

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

【问题讨论】:

  • 为什么要在Retrofit中使用同步调用? Http 请求应该在 Android 中异步发送。
  • @piotr.wittchen 有时你已经在一个线程中,那么使用同步调用非常有意义
  • 只是补充一点,我认为当您从服务器收到 401 后尝试在后台刷新令牌时也需要它。
  • 如果你使用的是Android Priority Job Queue(Job Manager)那么你在job中使用同步调用,它有它的用途,我个人不希望在ui类中有网络调用(活动)

标签: android retrofit


【解决方案1】:

您的猜测似乎正确,使用同步调用 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

【讨论】:

    【解决方案2】:

    很难找到这个。没有人真正谈论同步调用的错误处理。但我发现了一些东西。我不完全确定是否应该添加下一行(肯定应该为自定义错误添加,但事实并非如此)我找到了它here

    Foo doFoo() throws RetroFitError;
    

    同步调用应该发生在这样的 try catch 子句中:

    try{
        doFoo();
    }catch(RetroFitError e){
    
    }
    

    找到here

    【讨论】:

    猜你喜欢
    • 2017-01-14
    • 2016-03-30
    • 2016-03-03
    • 2011-08-14
    • 2017-05-23
    • 2017-01-01
    • 2023-03-20
    • 2016-11-13
    • 1970-01-01
    相关资源
    最近更新 更多