本文介绍了处理 Volley 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 onErrorResponse

下面是我的代码.

String url = MainActivity.strHostUrl+"api/delete_picture";
jobjDeleteImage = new JsonObjectRequest(Request.Method.POST, url, jobj, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        Log.e("Image response", response.toString());


    }
},  new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {

        Log.e("Volly Error", error.toString());

        NetworkResponse networkResponse = error.networkResponse;
        if (networkResponse != null) {
            Log.e("Status code", String.valueOf(networkResponse.statusCode));
        }
    }
});

我想在这里处理 com.android.volley.TimeoutError 以及其他一些错误代码,如 404、503 等和 Toast 消息.

I want to handle com.android.volley.TimeoutError and also some other error code like 404, 503 etc and Toast message here.

推荐答案

networkResponse 为空,因为在 TimeoutError 中没有从服务器接收数据——因此超时.相反,您需要在这些事件之一发生时显示通用客户端字符串.您可以使用 instanceof 检查 VolleyError 的类型以区分错误类型,因为您没有网络响应可以使用 - 例如:

The networkResponse is null because in a TimeoutError no data is received from the server -- hence the timeout. Instead, you need generic client side strings to display when one of these events occur. You can check for the VolleyError's type using instanceof to differentiate between error types since you have no network response to work with -- for example:

@Override
public void onErrorResponse(VolleyError error) {

    if (error instanceof TimeoutError || error instanceof NoConnectionError) {
        Toast.makeText(context,
                context.getString(R.string.error_network_timeout),
                Toast.LENGTH_LONG).show();
    } else if (error instanceof AuthFailureError) {
        //TODO
    } else if (error instanceof ServerError) {
       //TODO
    } else if (error instanceof NetworkError) {
      //TODO
    } else if (error instanceof ParseError) {
       //TODO
    }
}

这篇关于处理 Volley 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:17