繁体   English   中英

如何使用try-catch by注释包装方法?

[英]How to wrap a method with try-catch by annotation?

如果在方法调用中应忽略异常,则应编写例如以下内容:

public void addEntryIfPresent(String key, Dto dto) {
   try {
        Map<String, Object> row = database.queryForMap(key);
        dto.entry.put(row);
   } catch (EmptyResultDataAccessException e) {}
}

我正在尝试编写例如具有相同效果的自定义spring注释,但是可以仅将其应用于方法标头。 可能类似于以下内容:

@IgnoreException(EmptyResultDataAccessException.class) //this annotation does not exist
public void addEntryIfPresent(String key, Dto dto) {
   Map<String, Object> row = database.queryForMap(key);
   dto.entry.put(row);
}

如何创建这样的注释?

这是使用AspectJ的一种方法。

首先,定义一个方法级别的注释。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface IgnoreRuntimeException{

}

然后,为注释定义一个环绕方面。

@Component
@Aspect
public class ExceptionHandlingAdvice {

    @Around("@annotation(com.yourpackage.IgnoreRuntimeException) && execution(* *(..))")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        Object returnObject = null;
        // do something before the invocation
        try {
            // invoke method
            returnObject = joinPoint.proceed();
            // do something with the returned object
            return returnObject;
        } catch (Exception e) {
            // do something with the exception
        }
    }

}

然后,您可以在方法之上应用注释,以忽略异常。

@IgnoreRuntimeException
public void addEntryIfPresent(String key, Dto dto) {
    // ...
}

您还可以使用ProceedingJoinPoint的api检查批注的参数,以仅忽略要忽略的异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM