首页 > 解决方案 > 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

标签: springspring-bootspring-mvcexception

解决方案


也许是这样的?

@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
}
}

推荐阅读