java异常记录aop,AOP异常处理

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.

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();

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.

If it is just not possible to do this in Java, please let me know

Regardless of whether or not its possible to do this in Java, is there a way to intercept thrown Exception with AOP Alliance or do I have to go somewhere else. And if I have to go somewhere else, where? AspectJ?

Thanks!

解决方案

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值