异常处理和事后建议 [英] Exception handling and after advice
问题描述
我在 Spring Boot 中使用 AOP.在成功执行某些方法后,我在 AOP 中使用 @After 建议来进行一些数据库插入.有一种情况,如果该方法在某处抛出异常,那么我不想执行我的 @After
建议调用.
I am using AOP with spring boot. After some method execution successfully I am using @After advice in AOP to do some data base insertion. There is one case if the method throw an exception somewhere then I don't want to execute my @After
advice call.
我不知道我是否在 AOP 中捕获异常,我的 after 建议方法也将执行.
I don't have any idea if I catch exception in AOP also my after advise method will going to execute.
@After(value = "execution(* saveUpdateMeasures(..)) and args(addMeasure)")
public void afterAdviseMeasure(JoinPoint joinPoint,AddMeasures addMeasure) throws Exception {
logger.info("url is " + request.getRequestURL() + "?" + request.getQueryString());
saveUserLog(addMeasure.getUserId(), "add update measure",addMeasure.getReviewId());
}
因此,如果我的方法 saveUpdateMeasures()
成功执行而没有任何异常,那么只有我在寻找执行 afterAdviseMeasure
.任何帮助将不胜感激.
So if my method saveUpdateMeasures()
executed successfully without any exception then only I am looking for executing afterAdviseMeasure
. Any help will be appreciated.
推荐答案
请阅读 Spring AOP 手册,尤其是关于 建议类型.一般来说,在使用新技术之前阅读手册总是一个好主意.;-)
Please read the Spring AOP manual, especially the chapter about advice types. In general it is always a good idea to read a manual before using a new technology. ;-)
@After
总是在方法终止后执行,无论是否有异常.更专业的版本只运行@AfterThrowing
异常或@AfterReturning
定期.后者就是您要查找的内容,如果您想记录它,它甚至可以让您访问返回值.
@After
is always executed after a method terminates, no matter if there was an exception or not. More specialised versions only run@AfterThrowing
an exception or@AfterReturning
regularly. The latter is what you are looking for and it even gives you access to the return value if you like to log it or so.
不过,这些通知类型都不会让您处理异常,正如我也在此处解释的那样.为此,您需要使用 @Around
建议.
None of these advice types will let you handle the exception, though, as I also explain here. You need to use an @Around
advice for that.
这篇关于异常处理和事后建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!