Skip to main content

How to avoid HttpStatusCodeException using Spring RestTemplate



I have written a Rest client using the Spring's RestTemplate with the following code


 try {

              response = restTemplate.exchange( url,HttpMethod.POST, entity , JsonNode.class);

 }catch (HttpStatusCodeException codeException) {
       String responseBody = codeException.getResponseBodyAsString();
           ......................
 } catch(Exception ex)
{       
           ex.printStackTrace();
           ObjectMapper mapper = new ObjectMapper();
          JsonNode node = mapper.readTree(" { \"error\" : \"" + ex.getMessage() + "\" }" );

           response = new ResponseEntity<>(node, HttpStatus.INTERNAL_SERVER_ERROR );
 }

In the above code, I am not able to read the response body. This is the issue with the RestTemplate default error handler. In order to fix this issue, I have the following two options

a) Write my own Error Handler that implements ResponseErrorHandler
b) Write my own Error Handler that extends DefaultResponseErrorHandler

I prefer the second option as I have to only override the hasError method

public class MyErrorHandler extends DefaultResponseErrorHandler{

    @Override
    public boolean hasError( ClientHttpResponse response ) throws IOException {
        // TODO Auto-generated method stub
        return false;
    }

}

restTemplate.setErrorHandler( new MyErrorHandler() );


I am always returning the false as I want to handle the exceptions by my own. This method can be further optimized by checking for specific HTTP Status codes.
Now instead of  HttpStatusCodeException , I will get the proper ResponseEntity<?> and I can handle it accordingly to my needs.












Comments

  1. The discussion of HttpStatusCodeException highlights a common issue when using Spring's RestTemplate: the default error handling can turn an HTTP error response into an exception before the application gets the response body in the desired form. The article's two approaches—implementing ResponseErrorHandler directly or extending DefaultResponseErrorHandler—provide practical ways to customize that behavior while still preserving the error information returned by the remote service.

    This is an important consideration when building REST clients because handling unsuccessful HTTP responses is part of reliable API integration, not just exception management. A Spring Boot ReactJS Full Stack Developer Course can help developers understand how Spring Boot services communicate with REST APIs and how those responses can be consumed by a modern frontend.

    ReplyDelete
  2. The example also shows why a consistent response-handling strategy matters when an application needs to distinguish server errors, application errors, and successful responses. Customizing the error handler gives developers more control over how response bodies and HTTP status codes are processed. A Spring Boot NextJS Full Stack Developer Course is relevant for developers building this type of REST-based backend alongside Next.js applications.

    ReplyDelete
  3. Handling HTTP errors effectively is an important part of building reliable REST clients with Spring. The article highlights how RestTemplate's default error handling can affect response processing and explains how implementing a custom error handler by extending DefaultResponseErrorHandler provides a practical way to customize error detection. Properly handling error responses helps developers preserve useful response details and build more robust API integrations.

    Understanding HTTP status codes, response bodies, and exception handling is essential when developing and consuming RESTful services. RESTful API Course is relevant for developers who want to strengthen their knowledge of API communication, error handling, and reliable service integration.

    ReplyDelete

Post a Comment

Popular posts from this blog

Eclipse - Server Tomcat v8.5 Server at localhost failed to start.

When I try to launch the tomcat from Eclipse, I encountered the following error Server Tomcat v8.5 Server at localhost failed to start. Solution Step 1  Delete the .snap file located at the following location     eclipse workspace Path\ .metadata\.plugins\org.eclipse.core.resources Step 2 Delete the  tmp0  folder from the following path      eclipse workspace Path \.metadata\.plugins\org.eclipse.wst.server.core Step 3  Delete the server from servers list Step 4  Remove already added Tomcat Server      i)  Click on Define a new Server     ii)  Select Server Runtime Environments     iii) Select the Tomcat Server and remove it as follows Remove Selected Server Step 5 Make sure that correct version of Server is configured in Project Properties Step 6 Restart the Eclipse IDE.

hibernate-release-5.4.4.Final - Required Jars

Introduction Hibernate (Object Relational Mapping framework) is an implementation of Java Persistence API (JPA) specification.   Required Jars for Hibernate 5.4.4 Following Jars resided inside the required folder are the mandatory jars required for Hibernate 5.4.4 antlr-2.7.7.jar byte-buddy-1.9.11.jar classmate-1.3.4.jar dom4j-2.1.1.jar FastInfoset-1.2.15.jar hibernate-commons-annotations-5.1.0.Final.jar hibernate-core-5.4.4.Final.jar istack-commons-runtime-3.0.7.jar jandex-2.0.5.Final.jar javassist-3.24.0-GA.jar javax.activation-api-1.2.0.jar javax.persistence-api-2.2.jar jaxb-api-2.3.1.jar jaxb-runtime-2.3.1.jar jboss-logging-3.3.2.Final.jar jboss-transaction-api_1.2_spec-1.1.1.Final.jar stax-ex-1.8.jar txw2-2.3.1.jar Hibernate 5.4.4 release is compatible with  Java 8 or 11  JPA 2.2 References https://hibernate.org/orm/releases/5.4/

Intellij : How to add @author comment to every new class

 Introduction In this tutorial, we will learn how to add @author comments to every new class that we create. We can achieve it using either of the following two solutions Solution 1:  Automatically add @author comments to every new class using Files and Code Templates Open File -> Settings -> Editor -> File and Code Templates -> Includes Click on Includes . Under File Header , enter the following comments text /**  * @author ${USER}  * @Date ${DATE}   */ Intellij - add @author comments Solution 2: Autocompletion of @author Open File  ->  Settings  ->  Editor  -> Live Templates Select Java and then click on + button In Abbreviation, enter @a In template text , enter the following comments           /**             * @author ${USER}             * @Date ${DATE}            */ In o...