java - Hibernate 异常不断由 RuntimeException.class 而不是 HibernateException.class 处理

标签 java spring hibernate

我设置了一个 ControllerAdvice,其中有两个异常处理程序;一个用于任何 Hibernate 异常 (HibernateException.class),一个用于任何其他运行时异常 (RuntimeException.class)

@ExceptionHandler(HibernateException.class)
public String handleHibernateException(HibernateException exc, Model theModel) {

    String message = "An error has occured: " + exc.getLocalizedMessage() + "\r\n";

    myLogger.warning(message);

    theModel.addAttribute("exception", message);

    return "testing";
}


@ExceptionHandler(RuntimeException.class)
public String handleRuntimeExceptions(RuntimeException exc, Model theModel) {

    if (exc instanceof HibernateException) {

        return handleHibernateException((HibernateException) exc.getCause(), theModel);
    }   

    String message = "An error has occured: " + exc.getLocalizedMessage() + "\n"
            + exc.getCause().getCause().toString() + "\r\n";
    myLogger.warning(message);

    theModel.addAttribute("exception", message);

    return "testing";

我正在通过弄乱我的查询语句来测试这一点,这给了我一个 QuerySyntaxException; HibernateException 的子类。然而,它仍然由我的运行时异常方法处理。

最佳答案

我认为 @ExceptionHandler 与 QuerySyntaxException 的确切异常名称完全匹配。您可以尝试放入 QuerySyntaxException。

关于java - Hibernate 异常不断由 RuntimeException.class 而不是 HibernateException.class 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55988661/

相关文章:

java - MOEA 框架 - 实现方法存在问题

java - Spring MVC 无法解析 .jsp 文件

hibernate - 冲洗模式只能使用一次吗?

mysql - MariaDB/MySQL 查询区分大小写吗?

java - 具有相同模式 url 的多个路由

hibernate - 无法从 persistence.xml 创建连接

java - 将 int 数组转换为 int

java - Jython,我应该把我的 .py 文件放在哪里

java - 如何使用具有原始 int 键和原始 int 值的 Map?

java - Singleton Bean 中可能存在的竞争条件