我找不到一个好的解决方案:在我的 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 的预更新方法中抛出的异常,直接的异常是持久性无法发生。
但是,尝试使用我的自定义异常的以下方法永远不会达到:
@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
}
}
关于用于引起/包装异常的 Spring ExceptionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55733426/