How to re-throw exception in AspectJ around advise

后端 未结 3 1335
孤城傲影
孤城傲影 2021-02-09 10:19

I have some methods which throws some exception, and I want to use AspectJ around advise to calculate the execution time and if some exception is thrown and to log into error lo

3条回答
  •  礼貌的吻别
    2021-02-09 10:42

    you can avoid catching the exceptions and just use a try/finally block without the catch. And if you really need to log the exception you can use an after throwing advice, like this:

    public aspect AspectServerLog {
    
        public static final Logger ERR_LOG = LoggerFactory.getLogger("error");
    
        Object around() : call (* com.abc.Iface.* (..)) {
    
            StopWatch watch = new Slf4JStopWatch();
    
            try {
                return proceed();
            } finally {
                watch.stop(thisJoinPoint.toShortString());
            }
        }
    
        after() throwing (Exception ex) : call (* com.abc.Iface.* (..)) {
            StringBuilder mesg = new StringBuilder("Exception in ");
            mesg.append(thisJoinPoint.toShortString()).append('(');
            for (Object o : thisJoinPoint.getArgs()) {
                mesg.append(o).append(',');
            }
            mesg.append(')');
    
            ERR_LOG.error(mesg.toString(), ex);
        }
    
    }
    

提交回复
热议问题