I am using the Retrofit library to do REST calls to a service I am using.
If I make an API call to my service and have a failure, the service returns a bit of JSON
A much neater way to do this is to create a class that can do the parsing/conversion for you, one that you can call anytime, anywhere.
public class ApiError {
public String error = "An error occurred";
public ApiError(Throwable error) {
if (error instanceof HttpException) {
String errorJsonString = null;
try {
errorJsonString = ((HttpException)
error).response().errorBody().string();
} catch (IOException e) {
e.printStackTrace();
}
JsonElement parsedString = new
JsonParser().parse(errorJsonString);
this.error = parsedString.getAsJsonObject()
.get("error")
.getAsString();
} else {
this.error = error.getMessage() != null ? error.getMessage() : this.error;
}
}
}
You can now use this anywhere, like so
ApiError error = new ApiError(error)
error.error
This is all from this blog post (which I wrote).