I believe the approach provided by this answer https://stackoverflow.com/a/61422022/602506 is better than the others.
What's the approach? In your @ExceptionHandler method simply call response.sendError() to set the response status which Spring Boot's BasicErrorController uses later when putting together the response. For example:
@ExceptionHandler(EmptyResultDataAccessException.class)
public void handleEntityNotFoundException(EmptyResultDataAccessException e, HttpServletResponse response) throws IOException {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
Why is this better?
the response body will have the same format as any other exception handled by Spring, via the behavior of DefaultErrorAttributes (or your customized ErrorAttributes, if you provided one)
it still obeys Spring configuration properties such as server.error.include-exception and server.error.include-stacktrace, as well as query-parameter based controls such as ?trace=true
it works with any exception class, including exceptions from libraries which you therefore cannot annotate with @ResponseStatus