首页 > 解决方案 > Hibernate 异常一直由 RuntimeException.class 而不是 HibernateException.class 处理

问题描述

我有一个 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 的子类。然而,它仍然由我的运行时异常方法处理。

标签: javaspringhibernate

解决方案


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


推荐阅读