@ControllerAdvice exception handler method not get called

人盡茶涼 提交于 2019-12-05 08:03:58
Vishal Singh

You are missing @EnableWebMvc annotation in your Exception handler. Your Exception handler should be like this.

@EnableWebMvc
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({ApplicationException.class})
    public void notFount(){
        System.out.println("----------CaughtApplicationException-----------");
    }

    @ExceptionHandler({Exception.class})
    public void notFountGlobal(){
        System.out.println("----------CaughtApplicationException-----------");
    }

}

Also you need to tell exception handler method which exception you want to catch in which method. At last you can specify a method which can caught all other exception passing it Exception.class. The code snippet you post work for me. Hopefully it will resolve your problem.

In my case, the handler method is not called because of additional parameter in the method signature.

Not working:

@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handle404(HttpServletRequest request, Exception e,  @RequestHeader(value = "referer", required = false) final String referer) {
    ...
}

The referer parameter is what caused the handler method not being called. The problem is solved after removing the parameter.

Works:

@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handle404(HttpServletRequest request, Exception e) {
    ...
}

You need to declared the exception so that the method can be mapped to the exception type. You have two possibilities, either state the exception as an argument

public void notFount(ApplicationException exception){

or

add the type as a value attribute of your @ExceptionHandler annotation

 @ExceptionHandler(value = ApplicationException.class)

In addition, you most likely have a config issue, 'cause with the erroneus GlobalExceptionHandler that you've posted, the servlet wouldn't start-up, explicitly saying that no exception types are mapped to the method. Make sure that you're scanning the package where your GlobalExceptionHandler resides, by the looks of things, that is most likely your issue

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