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?
you can simply use "response. message(). toString()" which will give the same error string in a more readable format.
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With