我看到Guice和Spring在幕后使用AOP Alliance进行方法拦截,我一直在尝试弄清楚如何让AOP Alliance拦截和处理某些异常,这样我就不必在每个catch块中反复编写相同的代码。
但是在审查了剧本之后,看起来AOP联盟并没有提供任何方法来拦截抛出的Throwable,这种方式使得处理程序/拦截器可以做一些事情(记录异常等)。然后,确定是进一步传播异常,还是只恢复到抛出异常的行之后的下一行
HerpDerp hd = null;
if(hd == null)
throw new RuntimeException("Herpyl derp!");
Manny.pacquiao();我正在寻找一种AOP异常处理机制,它可以拦截RuntimeException并使用业务逻辑来决定是继续传播它,还是在Manny.pacquioa()调用时恢复。
如果在Java语言中不可能做到这一点,请让我知道在know
谢谢!
发布于 2012-06-11 23:16:48
您可以使用Spring AOP捕获异常,但我不知道这是否符合您对纯Java框架的要求。
使用Spring,您可以编写一个简单的AOP拦截器,如下所示:
@Aspect
public class ErrorInterceptor{
@AfterThrowing(pointcut = "execution(* com.mycompany.package..* (..))", throwing = "ex")
public void errorInterceptor(WidgetException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Error Message Interceptor started");
}
// DO SOMETHING HERE WITH EX
logger.debug( ex.getCause().getMessage());
if (logger.isDebugEnabled()) {
logger.debug("Error Message Interceptor finished.");
}
}
}但是没有办法返回到调用方法或在后续行上继续处理。然而,如果你在这里处理异常,它不会冒泡到链上,除非你自己重新抛出它。
发布于 2012-06-11 23:36:08
这是有原因的,它不存在。这将需要重写代码的块结构,就好像您首先编写了try/catch块一样。在我看来,这可能会对变量作用域和其他东西造成严重破坏。您要求AOP将字节码重写为类似以下代码的代码,这是一次相当大的重写。
HerpDerp hd = null;
try {
if(hd == null)
throw new RuntimeException("Herpyl derp!");
} catch(RuntimeException e) {
if (someConditionIsMet) {
throw e;
}
}
Manny.pacquiao();发布于 2012-06-08 20:04:25
要使用AspectJ“捕获”未捕获的异常,您可以使用以下方面:
pointcut uncaughtExceptionScope() :
(execution(* com.mycompany.myrootpackage..Main.main(..))
|| execution(* java.util.concurrent.Callable+.call())
|| execution(* java.lang.Runnable+.run())
));
after() throwing(Throwable t) : uncaughtExceptionScope() && !cflow(adviceexecution()) {
handleException(thisJoinPoint, t);
}
protected void handleException(JoinPoint jp, Throwable t)
{
// handle exception here
}我不认为“回到”执行点是可能的。
https://stackoverflow.com/questions/10947933
复制相似问题