我正在使用 Volley 库提供的 RequestFuture 进行同步 api 调用。 当状态 代码为 4xx/500 时,我需要处理错误响应。
try {
JSONObject response = future.get();
} catch (InterruptedException e) {
// exception handling
} catch (ExecutionException e) {
// exception handling
}
现在错误被 ExecutionException catch 子句捕获。如何从此错误中获取NetworkResponse。
如何重写 catch 子句中的 onErrorListener。
最佳答案
尝试使用此方法来捕获截击中的错误。另外请注意,在执行将来的请求时,您应该使用带有超时的 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");
}
关于error-handling - 处理请求 future Volley 调用的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34785194/