androidandroid-studioerror-handlinghttp-response-codes

Its going in else statement I'm not able to identify error


I am not getting any error but it is going in else statement.I Don't know how to resolve it help me about it.

if (response instanceof HttpResponseException) {
                    HttpResponseException exception = (HttpResponseException) response;
                    switch (exception.getStatusCode()) {
                        case 401:
                            Toast.makeText(mActivity, "Please login again", Toast.LENGTH_SHORT).show();
                            Utils.startActivityWithFinish(mActivity, PhoneNumberActivity.class);
                            break;
                        case 500:
                            Toast.makeText(mActivity, "Something went wrong", Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            break;
                    }
                }else{
                    Toast.makeText(mActivity, "Something went wrong", Toast.LENGTH_SHORT).show();
        
                 } 

Solution

  • This just means that response is not a HttpResponseException, but could be any other Exception or none at all (Successful?).

    To find out what kind of class it is, you can print the class name in your else-block:

    Toast.makeText(mActivity, "reponse is an instance of: " + response.getClass().getSimpleName(), Toast.LENGTH_SHORT).show();
    

    The name should give you a clue already. If it is another exception, it looks like your preceding try-catch is to general and catching away all exceptions. Replace it with a less general one:

    try {
        // Your networking code
    } catch (HttpResponseException httpResponseException) {
        response = httpResponseException;
    }
    

    Now the app should crash when running your code and deliver you the stacktrace with the information what is going wrong.