AOP异常处理 [英] AOP Exception Handling

查看:624
本文介绍了AOP异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到Guice和Spring使用AOP联盟进行方法拦截,我一直在试图找出如何让AOP联盟拦截和处理某些异常,所以我不必一直写$ / code>块

I see that Guice and Spring use AOP Alliance under the hood for method interceptions, and I've been trying to figure out how to get AOP Alliance to intercept and handle certain exceptions so I don't have to keep writing the same code over and over again inside every catch block.

但是,在查看了这个游戏之后,它看起来不像AOP联盟提供任何方式拦截投掷 Throwable ,使处理程序/拦截器能够执行某些操作(记录异常等),然后确定无论是否进一步传播异常,或只是恢复到抛出异常的行之后的下一行:

But after reviewing the play, it doesn't look like AOP Alliance provides any way to intercept thrown Throwables in such a way that the handler/interceptor can do some things (log the exception, etc.) and then determine whether or not to propagate the exception any further or to just recover back to the next line following the line which threw the exception:

HerpDerp hd = null;

if(hd == null)
    throw new RuntimeException("Herpyl derp!");

Manny.pacquiao();

我正在寻找一个AOP异常处理机制来拦截 RuntimeException ,并使用业务逻辑来决定是否继续传播它,或者在 Manny.pacquioa()调用中恢复。

I'm looking for an AOP exception handling mechanism that would intercept the RuntimeException and use business logic to decide whether to keep propagating it or to recover back at the Manny.pacquioa() call.


  • 如果在Java中不可能这样做,请让我知道

  • 无论它是否可能要在Java中做到这一点,有没有办法拦截抛出异常与AOP联盟,或者我必须去别的地方。如果我必须去别的地方去哪里?

谢谢!

推荐答案

p>您可以使用Spring AOP捕获异常,但是我不知道这是否符合您对纯Java框架的要求。

You can catch exceptions with Spring AOP, but I do not know if that matches your requirement for a pure Java framework.

使用Spring,您可以编写一个简单的AOP拦截器,如:

With Spring, you can write a simple AOP interceptor as something like:

@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.");
    }
}
}

但是没有办法返回到调用方法或继续处理后续行。但是,如果您处理此处的异常,除非您自行重新启动,否则不会冒泡。

but there is no way to return to the calling method or continue processing on the subsequent line. However if you handle the exception here, it won't bubble up the chain unless you rethrow it yourself.

这篇关于AOP异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆