6

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?

CherryBelle
  • 1,302
  • 7
  • 26
  • 46

3 Answers3

6

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();
        }
    }
}
Mayur Sojitra
  • 690
  • 7
  • 19
0

I think you will get the full response if you tried response.body.toString().

NIKHIL MAURYA
  • 289
  • 1
  • 15
  • try { String error = response.errorBody().string(); error = error.replace("\"", ""); Toast.makeText(getContext(), error, Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); } – Barungi Stephen Dec 30 '19 at 10:11
-2

Just use response.message()

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

    } else {
        // Handle error
        Log.i("Response message: ", response.message());
    }
}
Onur D.
  • 515
  • 3
  • 11