【问题标题】:Handle error for request future calls in volley在 volley 中处理请求未来调用的错误
【发布时间】:2016-01-14 08:53:53
【问题描述】:

我正在使用 Volley 库提供的 RequestFuture 进行 同步 api 调用。 当 status code 为 4xx/500 时,我需要处理错误响应。

    try {
  JSONObject response = future.get();
} catch (InterruptedException e) {
  // exception handling
} catch (ExecutionException e) {
  // exception handling
}

现在错误被 ExecutionException catch 子句捕获。如何从此错误中获取 NetworkResponse

如何在 catch 子句中覆盖 onErrorListener

【问题讨论】:

    标签: error-handling android-volley synchronous


    【解决方案1】:

    试试这个从截击中抓住错误。另外,在执行未来请求时请注意,您应该使用 get 超时,这样您就不会永远等待。

    try
    {
       JSONObject response = future.get(30,TimeUnit.SECONDS);
    }
    catch(InterruptedException | ExecutionException ex)
    {
       //check to see if the throwable in an instance of the volley error
       if(ex.getCause() instanceof VolleyError)
       {
           //grab the volley error from the throwable and cast it back
           VolleyError volleyError = (VolleyError)ex.getCause();
          //now just grab the network response like normal
          NetworkResponse networkResponse = volleyError.networkResponse;
       }                          
    }
    catch(TimeoutException te)
    {
       Log.e(TAG,"Timeout occurred when waiting for response");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      相关资源
      最近更新 更多