Geoff
Geoff

Reputation: 6649

Volley error output the error message sent from server side

Am using volley with php and returning an error with the following structure as seen in postman

{
  "name": "Exception",
  "message": "Unable to verify your accont",
  "code": 500,
  "type": "yii\\base\\UserException"
}

Now i would like to read the error message above so in my volley string request i have

    StringRequest stringRequest = new StringRequest(this.request_method, this.api_url,
            response -> {

             },
            error -> {
            //here process the error
            if (error instanceof ServerError || error instanceof AuthFailureError){
             NetworkResponse response = er.networkResponse;
             switch (response.statusCode){
              case 500:{
               HashMap<String, String> result = new Gson().fromJson(....); //stuck

               }
             }
            }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }         
    };

Am stuck on how to read the error message from volley error. How do i proceed with or without gson

I still want to use string request as i expect my response from php to be a json encoded string.

Upvotes: 3

Views: 809

Answers (3)

Parth Pitroda
Parth Pitroda

Reputation: 997

try to get response.errorbody from your api response

Upvotes: 0

Manohar
Manohar

Reputation: 23404

Use

String errorResponse = new String(error.networkResponse.data);

Then convert this string to your json object

Upvotes: 1

AskNilesh
AskNilesh

Reputation: 69724

Try this way to read Response from NetworkResponse

For kotlin

val response = er.networkResponse
val jsonError = String(response.data)
val responseObject = JSONObject(response)
val message = responseObject.optString("message")

for java

NetworkResponse response = er.networkResponse;
String responseData = new String(response.data,"UTF-8");
JSONObject responseObject =new  JSONObject(response)
String message = responseObject.optString("message")

Upvotes: 2

Related Questions