I am using Google Volley on the Android platform.
I am having a problem in which the error
parameter in onErrorResponse
is returning a null networkResponse
For the RESTful API I am using, I need to determine the Http Status Code which is often arriving as 401 (SC_UNAUTHORIZED) or 500 (SC_INTERNAL_SERVER_ERROR), and I can occasionally check via:
final int httpStatusCode = error.networkResponse.statusCode;
if(networkResponse == HttpStatus.SC_UNAUTHORIZED) {
// Http status code 401: Unauthorized.
}
This throws a NullPointerException
because networkResponse
is null.
How can I determine the Http Status Code in the function onErrorResponse
?
Or, how can I ensure error.networkResponse
is non-null in onErrorResponse
?
It turns out that it is impossible to guarantee that error.networkResponse is non-null without modifying Google Volley code because of a bug in Volley that throws the Exception NoConnectionError
for Http Status Code 401 (HttpStatus.SC_UNAUTHORIZED
) in BasicNetwork.java (134) prior to setting the value of networkResponse
.
Instead of fixing the Volley code, our solution in this case was to modify the Web Service API to send Http Error Code 403 (HttpStatus.SC_FORBIDDEN
) for the particular case in question.
For this Http Status Code, the value of error.networkResponse
is non-null in the Volley error handler: public void onErrorResponse(VolleyError error)
. And, error.networkResponse.httpStatusCode
correctly returns HttpStatus.SC_FORBIDDEN
.
Rperryng's suggestion of extending the Request<T>
class may have provided a solution, and is a creative and excellent idea. Thank you very much for the detailed example. I found the optimal solution for our case is to use the work-around because we are fortunate enough to have control of the web services API.
I might opt for fixing the Volley code in one location within BasicNetwork.java if I did not have access to making a simple change at the server.