Android Volley example with Error Handling

Spread knowledge

This article only covers how to handle error encountered while sending a network request with Volley library. To check complete Volley tutorial read this

 

android_error_handling

In my previous post we learnt how to send GET,POST request using volley in Android. As we had seen every Volley requests has two callbacks -one for success and one for failure. While this might make sense if the request is successful but would lead to confusion if the error callback is called – as the developer doesn’t know why the request actually failed. A request could fail due to multiple reasons

  • No internet connection
  • Very slow internet connection- com android volley timeoutError
  • An expired login session- com volley android volley AuthfailureError
  • Server is down or is unable to process the request- com android volley ServerError
  • Client not able to parse(read) the response

With these many reasons invoking the error callback it becomes difficult for both the developer and the user to figure out why a particular request failed. And this is what we are going to resolve today.

The VolleyError object returned along with the error callback will be helping us to figure out why a particular request failed.

@Override
public void onErrorResponse(VolleyError error) {

    if (error instanceof TimeoutError || error instanceof NoConnectionError) {
    //This indicates that the reuest has either time out or there is no connection

    } else if (error instanceof AuthFailureError) {
    //Error indicating that there was an Authentication Failure while performing the request

    } else if (error instanceof ServerError) {
     //Indicates that the server responded with a error response

    } else if (error instanceof NetworkError) {
        //Indicates that there was network error while performing the request

    } else if (error instanceof ParseError) {
        // Indicates that the server response could not be parsed

    }
}

 

Once we know why a request failed logging it and displaying a appropriate error message will not only be great user experience but will also lead the user to resolve the issue on his own rather than being stuck (User can switch to a different network once he sees his current network is too slow). Logging the error encountered could help the developers in debugging

If you want to have a look at complete working example of Volley. Please refer this article ->Volley Example


Spread knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *