问题
I want to handle NoHandlerException in Springboot app and return a custom error message. I added following to my application.properties and tried to override the error message.
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
Error doesn't hit the @ControllerAdvice... It is handled in defaulthandlerexceptionresolver . Any ideas?
回答1:
Putting @Order(Ordered.HIGHEST_PRECEDENCE)
and @ControllerAdvice
on the exceptions handler head, it means:
@ControllerAdvice
Specialization of @Component for classes that declare @ExceptionHandler, @InitBinder, or @ModelAttribute methods to be shared across multiple @Controller classes.
@Order
Defines the sort order for an annotated component. If we put as Ordered.HIGHEST_PRECEDENCE which is useful constant for the highest precedence value.
The code should be shown like this:
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ExceptionsHandler extends ResponseEntityExceptionHandler {
.....
}
REFERENCES:
@ControllerAdvice annotation documentation
@Order annotation documentation
来源:https://stackoverflow.com/questions/57958718/spring-boot-handle-nohandlerexception-in-controlleradvice