Spring-在@ControllerAdvice 中启动句柄NoHandlerException

Spring-boot handle NoHandlerException in @ControllerAdvice

我想在 Springboot 应用程序中处理 NoHandlerException 和 return 自定义错误消息。我在我的 application.properties 中添加了以下内容并试图覆盖错误消息。

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

错误没有命中@ControllerAdvice...它在 defaulthandlerexceptionresolver 中处理。有什么想法吗?

@Order(Ordered.HIGHEST_PRECEDENCE)@ControllerAdvice放在异常处理程序头上,这意味着:

@ControllerAdvice

Specialization of @Component for classes that declare @ExceptionHandler, @InitBinder, or @ModelAttribute methods to be shared across multiple @Controller classes.

@订单

Defines the sort order for an annotated component. If we put as Ordered.HIGHEST_PRECEDENCE which is useful constant for the highest precedence value.

代码应该是这样的:

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ExceptionsHandler extends ResponseEntityExceptionHandler {
    .....
}

参考资料:

@ControllerAdvice annotation documentation

@Order annotation documentation