gpt4 book ai didi

exception - 如何在 AspectJ 中围绕建议重新抛出异常

转载 作者:行者123 更新时间:2023-12-04 09:36:53 26 4
gpt4 key购买 nike

我有一些方法会抛出一些异常,我想使用 AspectJ 来计算执行时间,如果抛出一些异常,并登录到错误日志并通过重新抛出异常来继续流程。

我试图通过以下方式实现这一点,但 eclipse 说“未处理的异常类型”。

代码反对使用 aspectj 的人:-

public interface Iface {
public void reload() throws TException;

public TUser getUserFromUserId(int userId, String serverId) throws ResumeNotFoundException, TException;

public TUser getUserFromUsername(String username, String serverId) throws ResumeNotFoundException, TException;

public TResume getPartialActiveProfileFromUserId(int userId, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException;

public TResume getPartialActiveProfileFromUsername(String username, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException, TException;
}

代码方面:-
public aspect AspectServerLog {

public static final Logger ERR_LOG = LoggerFactory.getLogger("error");

Object around() : call (* com.abc.Iface.* (..)) {
Object ret;
Throwable ex = null;

StopWatch watch = new Slf4JStopWatch();

try {
ret = proceed();
}catch (UserNotFoundException e) {
ex = e ;
throw e ;
} catch (ResumeNotFoundException e) {
ex = e ;
throw e ;
} catch (Throwable e) {
ex = e ;
throw new RuntimeException(e);
}finally{

watch.stop(thisJoinPoint.toShortString());

if(ex!=null){
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);
numEx++;
}

}
return ret;
}
}

请帮助为什么这个 AspectJ 不起作用。

最佳答案

您可以避免捕获异常,只需使用 try/finally 块而不使用 catch。
如果你真的需要记录异常,你可以使用 after throwing 建议,如下所示:

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

}

关于exception - 如何在 AspectJ 中围绕建议重新抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10346750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com