Search code examples
androidandroid-volleyjsonobjectrequest

How to force the code to go to onErrorResponse in Volley JsonObjectRequest


A crash is reported in Volley JsonObjectRequest and exactly in its onErrorResponse block. I cannot change the webservice output to test onErrorResponse block and it's important to debug this code block.

Can anyone tell me how to force the code to go to this part?

JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "MY_URL", null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            // Which code should I add here to force the code to go to onErrorResponse

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            ...
            // I want to debug this code block

        }
    });

I tried response = null; in onResponse but it caused a crash and it didn't go to onErrorResponse.


Solution

  • As @Vivek Mishra said in comments, I tried to set an invalid URL like "https://stackoverflow.com/" instead of "MY_URL" (which was a valid API URL), and it went to onErrorResponse.

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "https://google.com/", null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
    
            // OnResponse Codes
    
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
    
            // OnError Codes
    
        }
    });