Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestTemplate handle exceptions

I am using Spring RestTemplate to make HTTP requests

This is my code:

public static ResponseEntity<String> makeRequest() {
    ResponseEntity<String> response = null;
    try {
         RestTemplate restTemplate = new RestTemplate();
         response = restTemplate.exchange(URI, HttpMethod.GET, null, 
         String.class);

     }catch (HttpStatusCodeException e) {
         System.out.println(e.getStatusCode());
     }catch (Exception e) {
         e.printStackTrace();
     }
         return response;
}

In the case of a 400 response from the server I am getting an exception and my method returns null value.

Is there any way to make Spring RestTemplate treats 400 HTTP code as 200 ?

like image 613
Zak FST Avatar asked Sep 08 '25 09:09

Zak FST


1 Answers

For a single place error handling use. Also included import statements

import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

RestTemplate restTemplate() {
    SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(2000);
    clientHttpRequestFactory.setReadTimeout(3000);
    RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override public boolean hasError(ClientHttpResponse response)
                throws IOException {
            try {
                //Do your stuff
                return super.hasError(response);
            } catch (Exception e) {
                logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
                return true;
            }
        }

        @Override public void handleError(ClientHttpResponse response)
                throws IOException {
            try {
                //Do your stuff
                super.handleError(response);
            } catch (Exception e) {
                logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
                throw e;
            }
        }
    });



    return restTemplate;
}
like image 166
Debopam Avatar answered Sep 09 '25 23:09

Debopam