作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一些方法会抛出一些异常,我想使用 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;
}
}
最佳答案
您可以避免捕获异常,只需使用 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/
我是一名优秀的程序员,十分优秀!