Jan 25, 2022

Retrofit2: Get the body from an error response

Retrofit2 is a nice library for making HTTP rest requests. It includes a static utility (CallUtils) for getting the result from your request, but if the api you’re calling doesn’t return a 2xx request it will throw an HttpException. Here is an example of using that CallUtils method.

Call<SomekindOfObject> call = .....;
return CallUtils.getResult(call);

The problem is when there is an error that HttpException does not return the message body, and oftentimes that body has information about why your request failed. To fix this problem I created a static method that captures the body and response code to return the body as part of the exception.

  public static <T> T getResult(retrofit2.Call<T> call) throws MyCustomException {
    if (call != null) {
      try {
        Response<T> response = call.execute();
        if (response.isSuccessful()) {
          return response.body();
        } else {
          String errorMessage = response.errorBody() != null ? response.errorBody().string() : "";
          throw new MyCustomException(response.code(), errorMessage);
      } catch (IOException ioe) {
        throw new MyCustomException(400, "error executing call");
    return null;

About the Author

Scott Bock profile.

Scott Bock

Principal Technologist

Scott is a Senior Software Engineer with over 12 years of experience using Java, and 5 years experience in technical leadership positions. His strengths include troubleshooting and problem solving abilities, excellent repertoire with customers and management, and verbal and written communication. He develops code across the entire technology stack including database, application, and user interface.

Leave a Reply

Your email address will not be published.

Related Blog Posts
Natively Compiled Java on Google App Engine
Google App Engine is a platform-as-a-service product that is marketed as a way to get your applications into the cloud without necessarily knowing all of the infrastructure bits and pieces to do so. Google App […]
Building Better Data Visualization Experiences: Part 2 of 2
If you don't have a Ph.D. in data science, the raw data might be difficult to comprehend. This is where data visualization comes in.
Unleashing Feature Flags onto Kafka Consumers
Feature flags are a tool to strategically enable or disable functionality at runtime. They are often used to drive different user experiences but can also be useful in real-time data systems. In this post, we’ll […]
A security model for developers
Software security is more important than ever, but developing secure applications is more confusing than ever. TLS, mTLS, RBAC, SAML, OAUTH, OWASP, GDPR, SASL, RSA, JWT, cookie, attack vector, DDoS, firewall, VPN, security groups, exploit, […]