【问题标题】:Exception is not thrown for page doesn't exist页面不存在不会引发异常
【发布时间】:2018-03-19 16:59:35
【问题描述】:

我已经用 @ControllerAdvice 定义了 ExceptionHandler 并捕获了以下内容

Exception.class、Throwable.class、SQLException.class

当用户进入服务器中不存在或不可用的页面时。日志中显示循环视图页面错误,并且未调用 ExceptionHandler。

使 API 错误在 CustomExceptionHandler 中被捕获的常见检查点是什么。不确定是否需要定义任何 tomcat 钩子。

使用 Spring Boot 2.0 和 Spring 5.0 版

谢谢。

【问题讨论】:

    标签: spring


    【解决方案1】:

    如果:用户输入了一个不存在的页面/资源,不会抛出异常。所以你的代码不起作用(我相信你的代码类似于下面的代码)

    @ControllerAdvice
    public class ErrorHandler {
        @ExceptionHandler(Exception.class) 
        public String handle() {
         ....
         return "error"
        }
    
    }
    

    为了使其正常工作,您需要从 ResponseEntityExceptionHandler 扩展 yourhandler 类

    @ControllerAdvice
    public class ErrorHandler extends ResponseEntityExceptionHandler {
    
       ...
    
    }
    

    而且你需要重写下面的方法

    • handleHttpMediaTypeNotSupported
    • handleHttpMediaTypeNotSupported

    详细指南可以从
    找到 - https://blog.jayway.com/2013/02/03/improve-your-spring-rest-api-part-iii/
    - http://www.baeldung.com/global-error-handler-in-a-spring-rest-api

    另一种方式,如果在所有一般情况下都有固定消息,您可以覆盖/error。

    【讨论】:

    • 非常感谢...我会检查
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多