java - 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 的子类。然而,它仍然由我的运行时异常方法处理。
解决方案
我认为@ExceptionHandler 与确切的异常名称 QuerySyntaxException 完全匹配。您能尝试放置 QuerySyntaxException。
推荐阅读
- java - 通过 Jackson/Spring REST 资源反序列化枚举字段
- entity-framework-core - 通过 EF Core 从数据库生成 C# 类
- flask - Flask 不适用于 Chrome,但适用于 Safari
- macos - Makefile 找不到可执行文件 - 没有这样的文件或目录
- shacl - Shacl sh:qualifiedValueShape 表达式缩写
- sql - 为什么在 case 命令中“不工作”?
- javascript - 如何在垂直列表中显示数组输出?
- vue.js - 如何禁用 vue-simple-calendar 中的特定日期?
- r - 如何将函数应用于向量的所有对
- rust - 如何在向量中打印json对象