Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

android - Handle Volley error

I want to handle and show some message in onErrorResponse

below is my code.

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));
        }
    }
});

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...