当我的调度程序servlet没有为请求的URL定义映射但尚未找到解决方案时,我一直在尝试处理全局情况。
这是我处理全局异常的类:
@ControllerAdvice public class GlobalExceptionHandlerController { @Value("${exception.view.default}") private String defaultExceptionView; private static final Logger LOGGER = Logger.getLogger(GlobalExceptionHandlerController.class); @ExceptionHandler(Exception.class) public ModelAndView notFoundException(Exception e) { LOGGER.error("Error ocurred: " + e.getMessage()); return new ModelAndView(defaultExceptionView) .addObject("code", "404") .addObject("name", "Page Not Found") .addObject("message", "We couldn't find requested resource"); } }我在@ExceptionHandler中尝试了很多不同的类,但没有对我有用。 处理程序工作正常 - 当我从其中一个控制器抛出异常而它没有在本地处理它直接进入这个全局处理程序。
有没有办法通过@ControllerAdvice执行这种异常处理?
I've been trying to handle globally a situation when my dispatcher servlet doesn't have defined mapping for requested url but haven't found the solution yet.
Here's my class for handling global exceptions:
@ControllerAdvice public class GlobalExceptionHandlerController { @Value("${exception.view.default}") private String defaultExceptionView; private static final Logger LOGGER = Logger.getLogger(GlobalExceptionHandlerController.class); @ExceptionHandler(Exception.class) public ModelAndView notFoundException(Exception e) { LOGGER.error("Error ocurred: " + e.getMessage()); return new ModelAndView(defaultExceptionView) .addObject("code", "404") .addObject("name", "Page Not Found") .addObject("message", "We couldn't find requested resource"); } }I tried many different classes within @ExceptionHandler but nothing worked for me. The handler works fine - when I throw exception from one of the controllers and it isn't handled locally it goes straight to this global handler.
Is there a way to perform that kind of exception handling by @ControllerAdvice?
最满意答案
是的,使用设置的setThrowExceptionIfNoHandlerFound配置DispatcherServlet
[...]当没有为此请求找到Handler时是否抛出NoHandlerFoundException 。 然后可以使用HandlerExceptionResolver或@ExceptionHandler控制器方法捕获此异常。
并按照它说的做,即。 为NoHandlerFoundException异常定义NoHandlerFoundException 。
Yes, configure your DispatcherServlet with setThrowExceptionIfNoHandlerFound which sets
[...] whether to throw a NoHandlerFoundException when no Handler was found for this request. This exception can then be caught with a HandlerExceptionResolver or an @ExceptionHandler controller method.
and do what it says, ie. define an @ExceptionHandler for a NoHandlerFoundException exception.
更多推荐
处理,@ExceptionHandler,exception,class,没有,电脑培训,计算机培训,IT培训"/> <meta
发布评论