4

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 ?

Zak FST
  • 361
  • 3
  • 6
  • 17
  • What do you mean by 'Is there any way to make Spring RestTemplate treats 400 HTTP code as 200'. What are you trying to achieve? – akortex Jan 07 '19 at 16:44
  • 1
    You're catching the exception and then choosing to return null. What do you want to happen instead? (You can't "treat 400 as 200" because they're not the same, but if you explain what you want to happen in the case of a 200, then perhaps we can help.) – chrylis -cautiouslyoptimistic- Jan 07 '19 at 17:18
  • Spring RestTemplate treats 400 HTTP code as an exception so my response variable is null, my client cannot get Http code and message code to know what hapend exactly. in case of 200, my response is not null so I can do this : response.getBody(); response.getStatusCode(); – Zak FST Jan 08 '19 at 08:47

2 Answers2

4

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;
}
Debopam
  • 3,198
  • 6
  • 41
  • 72
0

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