I am trying to map exceptions from my rest controllers to responses which have a body, and to do it in a central place.
I have tried this:
@Order(Ordered.HIGHEST_PRECEDENCE)@ControllerAdvicepublic class RestErrorResponseExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleExceptionInternal( Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { super.handleExceptionInternal(ex, body, headers, status, request); return ResponseEntity.status(status).body(Error.from(status)); }}
The problem is that the handler is never triggered.
If I define a custom method with @ExceptionHandler
in my rest controllers, or extend something that has @ExceptionHandler
, then all works well, but that introduces some bad design.
It is my understanding that Spring will first try to look in controller for exception handling methods, then it will check for registered handlers.
I am trying to verify the behaviour via WebMvcTest, and responses I'm getting are not the Error objects that I'm expecting.
Is there something I'm missing?