Hibernate异常始终由RuntimeException.class而不是HibernateException.class处理

时间:2019-05-05 03:48:01

标签: java spring hibernate

我设置了一个ControllerAdvice,带有两个异常处理程序;一个用于任何Hibernate异常(HibernateException.class),另一个用于任何其他Runtime异常(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的子类。但是,它仍然由我的运行时异常方法处理。

1 个答案:

答案 0 :(得分:0)

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