简体   繁体   English

通过AOP或其他方式拦截已处理(捕获)的异常

[英]Intercept a handled (caught) exception via AOP or in another way

Is there any way I read exception from below method and pass it to other method for track. 有什么办法可以从下面的方法中读取异常并将其传递给其他方法以进行跟踪。 Response of catch block is different from exception. catch块的响应与异常不同。

Either adding some annotation or spring AOP or any other way. 添加一些注释或spring AOP或任何其他方式。

public void function(){
  try{
    method();
  }
  catch(Exception e){
    return response;
  }
}

If you want to do it with AOP, you have @AfterThrowing annotation that you can use: 如果要使用AOP进行操作,则可以使用@AfterThrowing批注:

@AfterThrowing(pointcut = "execution(* example.*(..))", throwing = "ex")
public void logError(Exception ex) {
    ex.printStackTrace();
}

If you are using spring web and lombok you can just add @SneakyThrows to the method that throws checked exception and create a @org.springframework.web.bind.annotation.ExceptionHandler to handle the Exception type. 如果您使用的是Spring Web和@SneakyThrows ,则可以将@SneakyThrows添加到引发已检查异常的方法中,并创建一个@org.springframework.web.bind.annotation.ExceptionHandler以处理Exception类型。

You can have a method with an exception parameter: 您可以使用带有异常参数的方法:

public void handleException(Exception e) {
    e.printStackTrace(); //for example print it   
}

Then you can pass your exceptions to this method: 然后,您可以将异常传递给此方法:

try {
   //some code that can throw exception
} catch(Exception e) {
   handleException(e);
}

I think what you want is to intercept an exception handler, not a thrown exception. 我认为您想要的是拦截异常处理程序,而不是引发的异常。 For that you need to switch from Spring AOP to AspectJ mode as explained in the Spring manual . 为此,您需要按照Spring手册中的说明从Spring AOP切换到AspectJ模式。

For more details on the AspectJ handler() pointcut which does what you want, see my answers with code examples here: 有关可以执行所需操作的AspectJ handler()切入点的更多详细信息,请在此处查看我的代码示例答案:

The handler() pointcut is also described in the AspectJ documentation . AspectJ文档中也描述了handler()切入点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM