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

南笙酒味 提交于 2020-05-13 18:12:00

问题


If an exception should be ignored inside a method call, one would write eg the following:

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

I'm trying to write eg a custom spring annotation that has the same effect, but could just be applied to the method header. That could look similar to the following:

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

How could such an annotation be created?


回答1:


Here is a way of doing it with AspectJ.

First of all, define a method level annotation.

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

}

Then, define an around aspect for the annotation.

@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
        }
    }

}

You can then apply the annotation on top of your methods to ignore exceptions.

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

You can also check the parameters of the annotation using the api of ProceedingJoinPoint to ignore only the exceptions that you'd like to ignore.



来源:https://stackoverflow.com/questions/52924708/how-to-wrap-a-method-with-try-catch-by-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!