Spring-boot handle NoHandlerException in @ControllerAdvice

ぐ巨炮叔叔 提交于 2020-12-12 05:14:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!