Zak FST
Zak FST

Reputation: 371

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 ?

Upvotes: 4

Views: 14475

Answers (2)

Pradeep Virtuele
Pradeep Virtuele

Reputation: 83

If you use a global exception handler add the below method or check this

https://www.javaguides.net/2018/09/spring-boot-2-exception-handling-for-rest-apis.html add below method in GlobalExceptionHandler class

@ExceptionHandler({HttpClientErrorException.class, HttpStatusCodeException.class, HttpServerErrorException.class})
    @ResponseBody
    public ResponseEntity<Object> httpClientErrorException(HttpStatusCodeException e) throws IOException {
        BodyBuilder bodyBuilder = ResponseEntity.status(e.getRawStatusCode()).header("X-Backend-Status", String.valueOf(e.getRawStatusCode()));
        if (e.getResponseHeaders().getContentType() != null) {
            bodyBuilder.contentType(e.getResponseHeaders().getContentType());
        }
        return bodyBuilder.body(e.getResponseBodyAsString());
    }

Upvotes: 0

Debopam
Debopam

Reputation: 3356

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;
}

Upvotes: 4

Related Questions