【发布时间】:2019-09-08 01:08:00
【问题描述】:
我找不到好的解决方案:在我的 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 的预更新方法中抛出的异常,直接的异常是 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
【问题讨论】:
-
ControllerAdvice 是完全不起作用还是在某些情况下不起作用?
-
只是不为 Caused-By 工作,在所有其他情况下工作
标签: spring spring-boot spring-mvc exception