【问题标题】:Getting UndeclaredThrowableException instead of my own exception获取 UndeclaredThrowableException 而不是我自己的异常
【发布时间】:2011-07-26 07:08:37
【问题描述】:

我有以下代码

public Object handlePermission(ProceedingJoinPoint joinPoint, RequirePermission permission) throws AccessException, Throwable {
    System.out.println("Permission = " + permission.value());
    if (user.hasPermission(permission.value())) {
        System.out.println("Permission granted ");
        return joinPoint.proceed();
    } else {
        System.out.println("No Permission");
        throw new AccessException("Current user does not have required permission");
    }

}

当我使用没有权限的用户时,我得到java.lang.reflect.UndeclaredThrowableException 而不是AccessException

【问题讨论】:

标签: java aop aspect


【解决方案1】:

AccessException 是一个检查异常,但它是从未在其throws 子句中声明它的方法抛出的(实际上 - 从拦截该方法的方面)。这是 Java 中的异常情况,因此您的异常用 UndeclaredThrowableException 包裹,未选中。

要获得您的异常,您可以在被切面拦截的方法的throws 子句中声明它,或者使用另一个未经检查的异常(即RuntimeException 的子类)而不是AccessException

【讨论】:

  • +1。我只想补充一点,在这些情况下UndeclaredThrowableException 包装了原始异常; getCause() 将返回 AccessException
  • 我在拦截的方法中声明了AccessException。更改 AccessException 以扩展 RuntimeException 有效。
  • 如果您是被UndeclaredThrowableException 捕获的代码的作者,阅读this post that has some details 可能会很好
  • @EdgeCaseBerg 和其他任何人,我想我被代理问题抓住了,但后来使用 throw new ValidationException('delete.failure',s.errors) - 然后返回正确的消息而不是 UndeclaredThrowableException 这就是 RuntimeException返回
  • 在我的情况下,在方法中声明 throws ClassNotFoundException 不起作用,但将异常包装在 RuntimeException 中确实有帮助 (throw new RuntimeException(e))。对于某些情况:我在 gradle @TaskAction 带注释的方法中使用它
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 1970-01-01
相关资源
最近更新 更多