Reputation: 51
I am working on a project that implements a common exception handler like this:
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleException(final Exception e) {
log.error(e.getMessage(), e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Now I want to use a rest template that isn't affected by this exception handling, but no matter what I try all exeptions are handled by the common handler. Any idea how I can utilize a rest template with a custom error handler that overrides the one above?
Modifications on the common exception handler are not possible, so I have to find a way to work around it.
Upvotes: 2
Views: 552
Reputation: 1157
I suggest two solutions:
@RestControllerAdvice
, this will may be lead to duplicate exceptionstry {
return restTemplate.postForObject("http://your.url.here", "YourRequestObjectForPostBodyHere", YourResponse.class);
} catch (HttpClientErrorException | HttpServerErrorException httpClientOrServerExc) {
if (HttpStatus.NOT_FOUND.equals(httpClientOrServerExc.getStatusCode())) {
// your handling of "NOT FOUND" here
// e.g. throw new RuntimeException("Your Error Message here", httpClientOrServerExc);
} else {
// your handling of other errors here
}
Upvotes: 1