spring - Spring ExceptionHandler for Caused By / Wrapped Exception
问题描述
我找不到一个好的解决方案:在我的 Spring Boot 应用程序中,作为一种@ExceptionHandler
方法,我需要定义一个处理程序,而不是针对特定异常,而是针对由特定异常(即包装异常)引起的任何异常。
示例:有时我会得到这个:
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:541) ~[spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746) ~[spring-tx-5.1.4.RELEASE.jar:5.1.4.RELEASE]
... 121 common frames omitted
Caused by: custom.TechRoleException: My custom TechRoleException
at myapp.method1[..]
at myapp.methodOuter[..]
我的自定义TechRoleException
是我在一些 Hibernate EventListener 的 pre-update 方法中抛出的异常,直接的异常是 Persistence 无法发生。
但是,从未达到以下尝试使用我的自定义异常的方法:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(TechRoleException.class)
public String techRoleException(HttpServletRequest request, Exception ex) {
System.out.println("Got here");
return "home";
}
}
这是一个类似的线程,其中答案是错误的并且没有回答这个问题: @ExceptionHandler for Wrapped Exception / getCause() in Spring
解决方案
也许是这样的?
@ExceptionHandler(Exception.class)
public String techRoleException(HttpServletRequest request, Exception ex) {
if(ex instanceof TechRoleException) {
System.out.println("Got here");
return "home";
} else {
throw ex; //or something else
}
}
推荐阅读
- lambda - @onclick="(() => SomeMethod(参数))"
- django - 如何从表单中排除字段?
- python - Pandas 来自其他 DataFrames 的多个 DataFrames
- c++ - 项目中同一头文件的多个包含:C vs C++
- flutter - 如何将状态从子小部件提升到另一个子小部件
- python - 从 pyqt5 按钮更新 matplotlib 图表时出现问题
- c - 将文本文件行存储到数组中
- wordpress - 有人在 Wordpress 上使用 Magazinenews 主题来说明将 Elementor 的 the_content 代码放在哪里?
- graphql - 尝试使用 useQuery 钩子测试组件但 onCompleted 导致问题
- android - 像素 2 上的 Mopub 横幅