如何在通用异常处理时获取到方法名称(获取注解参数JoinPoint)

1.背景

很多时候我们在梳理公共异常时,需要获取到接口的而具体名称,便于很好的提示是那个接口错误了

2.实现逻辑

1.在controller方法上的注解上写方法名称,一般使用了swagger都有方法名称;

2.使用aop通过JoinPoint,使用反射拿到注解上的方法名称;

3.把方法名称放到ThreadLocal里面;

4.在公用异常处理的地方从ThreadLocal里面获取到方法名称;

...搞定!

3.具体代码

1.在controller方法上的注解上写方法名称,一般使用了swagger都有方法名称;

 

 

 2.使用aop通过JoinPoint,使用反射拿到注解上的方法名称;

 /**
     * @Description 获取注解中对方法的描述信息 用于Controller层注解
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws ClassNotFoundException {
        String description = "";
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();//目标方法名
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        // 获取类上的注解
        Annotation annotation1 = targetClass.getAnnotation(Api.class);
        if (annotation1 != null) {
            String[] tags = ((Api) annotation1).tags();
            for (String tag : tags) {
                description += tag;
            }
        }
        // 获取方法上的注解
        Method[] methods = targetClass.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    ApiOperation annotation = method.getAnnotation(ApiOperation.class);
                    description += annotation == null ? "未命名接口" : annotation.value();
                    break;
                }
            }
        }
        return description;
    }

 

3.把方法名称放到ThreadLocal里面;

调用set方法即可

public class ThreadLocalUtil {
    private static ThreadLocal<String> localVar = new ThreadLocal<>();

    public static void set(String name) {
        localVar.set(name);
    }

    public static String get() {
        String s = localVar.get();
        localVar.remove();
        return s;
    }

    public static void remove() {
        localVar.remove();
    }

}

 

4.在公用异常处理的地方从ThreadLocal里面获取到方法名称;

 

 完美!

posted @ 2020-09-28 15:38  李东平|一线码农  阅读(2148)  评论(0编辑  收藏  举报