7

我有一些引发异常的方法,我想使用 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 不起作用。

4

3 回答 3

12

您可以避免捕获异常,只需使用没有捕获的 try/finally 块。如果您真的需要记录异常,您可以使用 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);
    }

}
于 2012-04-28T00:50:38.383 回答
6

恐怕您不能编写建议来抛出未声明为在匹配的连接点抛出的异常。每: http: //www.eclipse.org/aspectj/doc/released/progguide/semantics-advice.html:“建议声明必须包含一个 throws 子句,列出主体可能抛出的检查异常。这个检查异常列表必须与通知的每个目标连接点兼容,否则编译器会发出错误信号。”

关于改善这种情况的 aspectj 邮件列表已经讨论过 - 请参阅这样的线程:http: //dev.eclipse.org/mhonarc/lists/aspectj-dev/msg01412.html

但基本上你需要做的是为每个异常声明变体提供不同的建议。例如:

Object around() throws ResumeServiceException, ResumeNotFoundException, TException: 
  call (* Iface.* (..) throws ResumeServiceException, ResumeNotFoundException, TException) {

这将在任何有这 3 个例外的地方提供建议。

于 2012-04-27T17:25:23.933 回答
3

有一个“丑陋”的解决方法——我在 Spring4 中找到了它们AbstractTransactionAspect

Object around(...): ... {
    try {
        return proceed(...);
    }
    catch (RuntimeException ex) {
        throw ex;
    }
    catch (Error err) {
        throw err;
    }
    catch (Throwable thr) {
        Rethrower.rethrow(thr);
        throw new IllegalStateException("Should never get here", thr);
    }
}

/**
 * Ugly but safe workaround: We need to be able to propagate checked exceptions,
 * despite AspectJ around advice supporting specifically declared exceptions only.
 */
private static class Rethrower {

    public static void rethrow(final Throwable exception) {
        class CheckedExceptionRethrower<T extends Throwable> {
            @SuppressWarnings("unchecked")
            private void rethrow(Throwable exception) throws T {
                throw (T) exception;
            }
        }
        new CheckedExceptionRethrower<RuntimeException>().rethrow(exception);
    }
}
于 2017-11-28T15:59:25.587 回答