AOP 异常处理 [英] AOP Exception Handling

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

问题描述

我看到 Guice 和 Spring 在后台使用 AOP Alliance 进行方法拦截,我一直在尝试弄清楚如何让 AOP Alliance 拦截和处理某些异常,这样我就不必继续编写相同的代码了在每个 catch 块中一遍又一遍地编写代码.

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 联盟抛出的异常,或者我必须去其他地方.如果我必须去别的地方,去哪里?方面J?

谢谢!

推荐答案

您可以使用 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天全站免登陆