Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Error Body Response with Retrofit 2

I'm using Retrofit 2 and I need to handle response error in JSON format. Below is the example of the response body.

{
    "success": false,
    "error": {
        "message": {
            "name": [
                "This input is required."
            ]
        }
    }
}

message contains list of fields with errors which means the value is dynamic. Therefore, one of the possible solutions is by parsing the response body as JSON Object. I tried to get the error body using response.errorBody().string()

@Override
public void onResponse(final Call<Category> call, final Response<Category> response) {
    if (response.isSuccessful()) {

    } else {
        // Handle error
        String errorBody = response.errorBody().string();
    }
}

Unfortunately, printing the errorBody I can only get the following result {"success":false,"error":{"message":{"name":[""]}}} Is Retrofit limiting the errorBody object depth? What should I do to get the full response body that can be parsed?

like image 937
CherryBelle Avatar asked Oct 08 '18 19:10

CherryBelle


People also ask

How do I get error response in retrofit?

you can simply use "response. message(). toString()" which will give the same error string in a more readable format.


1 Answers

Try this snippet I used this in my retrofit. and getting dynamic error messages solution

@Override
public void onResponse(final Call<Category> call, final Response<Category> response) {
    if (response.isSuccessful()) {

    } else {
        try {
            String errorBody = response.errorBody().string();

            JSONObject jsonObject = new JSONObject(errorBody.trim());

            jsonObject = jsonObject.getJSONObject("error");

            jsonObject = jsonObject.getJSONObject("message");

            Iterator<String> keys = jsonObject.keys();
            String errors = "";
            while (keys.hasNext()) {
                String key = keys.next();
                JSONArray arr = jsonObject.getJSONArray(key);
                for (int i = 0; i < arr.length(); i++) {
                    errors += key + " : " + arr.getString(i) + "\n";
                }
            }
            Common.errorLog("ERRORXV", errors);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
like image 59
Mayur Sojitra Avatar answered Oct 24 '22 09:10

Mayur Sojitra