Hary
Hary

Reputation: 1217

ResponseEntity object with error status code returned by a Rest service in its response always causes exception in the caller

I have two spring boot rest services. One calls the other.

The callee returns response like this (programmed that way) in case of any internal error

ResponseEntity<String> responseEntity = new ResponseEntity<String>(jsonString, responseHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
return responseEntity;

The caller calls the other callee like this:

ResponseEntity<String> responseEntity ;
try {
    responseEntity = restTemplate.postForEntity(url, entity, String.class);

    if (responseEntity.getStatusCode() != "200"{
         //do something here
    }
    else{
     //do something else here
    }
}
catch(Exception ex){
   //do something here
}

Now the problem is that whenever callee inserts an error HttpStatus code in the returned ResponseEntity object like INTERNAL_ERROR, it always raises and exception in the caller and goes in the catch block of the caller. If it returns 200 then, all goes hunky dory in the caller.

My question is, why does it raise an exception in the caller when the Callee inserts an error HttpStatus code in the ResponseEntity return object and why can't I just fetch the ResponseEntity object in the caller as is regardless of the HttpStatus code inserted by the callee ?

Upvotes: 1

Views: 1306

Answers (1)

Arnold Galovics
Arnold Galovics

Reputation: 3416

As you can see in thre RestTemplate documentation, by default it's using the DefaultResponseErrorHandler which will end up throwing an exception in case an error happens.

This template uses a SimpleClientHttpRequestFactory and a DefaultResponseErrorHandler as default strategies for creating HTTP connections or handling HTTP errors, respectively.

If you don't want this logic, you can set a custom error handler through RestTemplate#setErrorHandler

Upvotes: 1

Related Questions