How to get error message description using Volley
The data field of networkResponse is a JSON string of the form:
{"response":false,"msg":"Old Password is not correct."}
So you need to get the value corresponding to "msg" field, like this (ofcourse with all exception catching):
String responseBody = new String(error.networkResponse.data, "utf-8");
JSONObject data = new JSONObject(responseBody);
String message = data.optString("msg");
Tested with Volley 1.1.1
Try with this custom method:
public void parseVolleyError(VolleyError error) {
try {
String responseBody = new String(error.networkResponse.data, "utf-8");
JSONObject data = new JSONObject(responseBody);
JSONArray errors = data.getJSONArray("errors");
JSONObject jsonMessage = errors.getJSONObject(0);
String message = jsonMessage.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
} catch (UnsupportedEncodingException errorr) {
}
}
It will show toast with error message from the request. Call this in onErrorResponse method in your volley request:
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
parseVolleyError(error);
}
}
IMO, you should override parseNetworkError
as below:
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
String json;
if (volleyError.networkResponse != null && volleyError.networkResponse.data != null) {
try {
json = new String(volleyError.networkResponse.data,
HttpHeaderParser.parseCharset(volleyError.networkResponse.headers));
} catch (UnsupportedEncodingException e) {
return new VolleyError(e.getMessage());
}
return new VolleyError(json);
}
return volleyError;
}
Then, inside onErrorResponse(VolleyError error)
, you can use Log.e(LOG_TAG, error.toString());
for example. Hope it helps!
you have to override parseNetworkError and deliverError methods and you can get errormessage from them.