I'm writing a Web application that makes downstream calls using RestTemplate. If the underlying service returns a 401 Unauthorized, I want to also return a 401 to the calling application; the default behavior is to return a 500. I want to keep the default Spring Boot error response as provided by BasicErrorController
; the only change I want is to set the status code.
In custom exceptions, I'd just annotate the exception class with @ResponseStatus
, but I can't do that here because HttpClientErrorException.Unauthorized
is provided by Spring. I tried two approaches with @ControllerAdvice
:
@ExceptionHandler(HttpClientErrorException.Unauthorized.class)
@ResponseStatus(UNAUTHORIZED)
public void returnsEmptyBody(HttpClientErrorException.Unauthorized ex) {
}
@ExceptionHandler(HttpClientErrorException.Unauthorized.class)
@ResponseStatus(UNAUTHORIZED)
public void doesNotUseBasicErrorController(HttpClientErrorException.Unauthorized ex) {
throw new RuntimeException(ex);
}
How can I configure MVC to continue to use all of the built-in Boot error handling except for explicitly overriding the status code?
You can customize the error handler of the RestTemplate to throw your custom exception, and then handle that exception with the @ControllerAdvice as you mentioned.
Something like this: