Prateekro Prateekro - 2 months ago 21
JSON Question

Send volley error response to switch case to handle error

I want to put this error in switch statement. where I have the whole statement and I just want to put this error response code.

Error: E/Volley: [205] BasicNetwork.performRequest: Unexpected response code 409 for https://api.abc.com:3211/newuser

new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(error != null && error.getMessage() != null)
{
Log.e("Response error", error.getMessage());
}
switch (error.toString()){
case "409" : errorBox.setText("username already exists");
break;
case "410" : errorBox.setText("email already exists");
break;
case "411" : errorBox.setText("xyz already exists");
break;
case "413" : errorBox.setText("abc already exists");
break;
case "414" : errorBox.setText("username invalid ");
break;
default :
Log.d(TAG, "onErrorResponse: "+error.toString());
break;
}
}
}


P.S.: Switch should process only < 409 > the response code.

Answer

Use statusCode which is an int. docs

  new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(error != null && error.getMessage() != null)
                {
                    Log.e("Response error", error.getMessage());
                }
                switch (error.networkResponse.statusCode){
                    case 409 : errorBox.setText("username already exists");
                        break;
                    case 410 : errorBox.setText("email already exists");
                        break;
                    case 411 : errorBox.setText("xyz already exists");
                        break;
                    case 413 : errorBox.setText("abc already exists");
                        break;
                    case 414 : errorBox.setText("username invalid ");
                        break;
                    default :
                        Log.d(TAG, "onErrorResponse: "+error.toString());
                        break;
                }
            }
        }

You should also put a nullity check to verify the 'networkResponse' is not null.

if(error.networkResponse!= null){
  // switch code
}
Comments