java - how to let @ExceptionHandlers handle specific exceptions before defaulting to an Exception handler for any Runtime error?
问题描述
I want to use an @ExceptionHandler to handle any Hibernate exceptions. If the exception is not a Hibernate exception, then an @ExceptionHandler for Runtime errors handles the exception.
the problem is, Runtime exception is always taking precedence over the Hibernate exception handler. meaning, any hibernate exception that occurs is being handled by the general Runtime exception handler instead.
How can I ensure that Hibernate exceptions are handled by its exception handler, rather than being handled by Runtime exceptions?
'@ExceptionHandler(HibernateException.class)
public String handleHibernateException(HibernateException exc, Model theModel) {
String message = "An error has occured: " + exc.getLocalizedMessage() + "\n" + exc.getCause().toString()
+ "\r\n";
myLogger.warning(message);
theModel.addAttribute("exception", message);
return "testing";
}
// handle any other runtime/unchecked exception and log it
@ExceptionHandler(RuntimeException.class)
public String handleRuntimeExceptions(RuntimeException exc, Model theModel) {
String message = "An error has occured: " + exc.getLocalizedMessage() + "\n" + exc.getCause().toString()
+ "\r\n";
myLogger.warning(message);
theModel.addAttribute("exception", message);
return "testing";
}'
解决方案
您可以通过以下方式检查异常是否是 HibernateException 的实例:
@ExceptionHandler(RuntimeException.class)
public String handleRuntimeExceptions(RuntimeException exc, Model theModel) {
if (exc instanceof HibernateException) {
return handleHibernateException((HibernateException) exc.getCause(), theModel);
} else if (exc.getCause() instanceof HibernateException) {
HibernateException hibernateException = (HibernateException) exc.getCause();
return handleHibernateException(hibernateException, theModel);
}
String message = "An error has occurred: " + exc.getLocalizedMessage() + "\n" + exc.getCause().toString() + "\r\n";
myLogger.warning(message);
theModel.addAttribute("exception", message);
return "testing";
}
推荐阅读
- bash - 从 Bash 中的特定行反向搜索模式
- java - Java 中的 AWS Lambda 请求 gzip 编码
- flutter - 如何在 Flutter Provider 中正确初始化 Future
- python - wrapInstance 后 PYQT Maya QMouseEvent 将不起作用
- python-3.x - python3中井字游戏的循环问题
- microsoft-graph-api - 在搜索字符串中传递@g 时,图形 api 返回空结果
- python - 与 Pymssql / Adaptive Server 连接失败(Windows.net 与 Azure.com)
- postgresql - PostgreSQL,plpython3u 函数。os.getenv 没有找到环境变量
- reactjs - 在反应中从配置中消耗 jsx
- cucumber - Cucumber 5.0.0 和 springboot 多个场景在一个特性文件中