【发布时间】:2013-08-31 04:13:39
【问题描述】:
请随时编辑问题或询问有关任务的更多详细信息。
我知道我可以使用aspectJ 作为以下方法的log ArithmeticException,
public void afterThrowingAspect(){
System.out.println("This is afterThrowingAspect() !");
int i=2/0;
System.out.println("i value : "+i);
}
AspectJ 类有,
@AfterThrowing(pointcut = "execution(* com.pointel.aop.test1.AopTest.afterThrowingAspect(..))",throwing= "error")
public void logAfterError(JoinPoint joinPoint,Throwable error) {
System.out.println("Hi jacked Method name : " + joinPoint.getSignature().getName());
log.info("Method name : " + joinPoint.getSignature().getName());
log.info("Error report is : " + error);
}
通常我可以使用TRY 和CATCH 块和log 处理异常,每个CATCH 块中的错误为,
public void someMehtod(){
try{
int i=2/0;
System.out.println("i value : "+i);
}catch{ArithmeticException err){
log.info("The exception you got is : " + err);
}
}
但我不喜欢在我的项目的所有 java 类中对每个 catch 块单独执行 logging,例如,
log.info("The exception you got is : " + err);
我想在我的应用程序中使用aspectJ 类在CATCH 块中执行logging。
希望大家能理解我的问题。谢谢。
【问题讨论】:
-
如果将@AfterThrowing 切入点定义为
pointcut = "execution(* com.pointel.*(..))",则每次在com.pointel 的包和子包中引发异常时都会触发@AfterThrowing 方面。那是你想要的吗? -
请看我编辑的问题。
-
@Julien 我不需要记录
@AfterThrowing方法。我需要使用aspectJ在 catch 块中记录exception。我这可能吗? -
您不能建议方法内的catch-block。只能建议方法的进入和退出,而不是内容。如果您在同一方法内的某个方法中捕获发生的异常,则仅当您从 catch 块将异常抛出到调用堆栈中更高的位置(并在方法完成后将其记录在 @ 中)时,才能使用 aspectj 记录异常后投掷)。
-
@Sheltem 感谢您的快速回复。你能不能给我一个小例子。这将有助于我在我的代码中轻松理解和实现。
标签: java spring logging exception-handling aspectj