【问题标题】:Handling "No mapping found for HTTP request in DispatcherServlet" situation处理“DispatcherServlet 中未找到 HTTP 请求的映射”情况
【发布时间】:2016-01-07 14:22:17
【问题描述】:

我一直在尝试全局处理我的调度程序 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 执行这种异常处理?

【问题讨论】:

    标签: java spring model-view-controller exception-handling dispatcher


    【解决方案1】:

    是的,将DispatcherServlet 配置为setThrowExceptionIfNoHandlerFound 设置

    [...] 当没有Handler 时是否抛出NoHandlerFoundException 找到了这个请求。然后可以用 HandlerExceptionResolver@ExceptionHandler 控制器方法。

    并按照它所说的去做,即。为NoHandlerFoundException 异常定义@ExceptionHandler

    【讨论】:

    • 谢谢,成功了!不知道该调度程序配置选项。
    猜你喜欢
    • 1970-01-01
    • 2021-08-01
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2016-06-11
    • 1970-01-01
    相关资源
    最近更新 更多