zoukankan      html  css  js  c++  java
  • 如何在通用异常处理时获取到方法名称(获取注解参数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里面获取到方法名称;

     完美!

  • 相关阅读:
    PHP thinkPHP6.0 部署
    ch09 Sql导入语句
    自定义map 搜索
    MySql 语句
    自定义Mappter
    三袋米的故事
    WPF中实现文件夹对话框(OpenFileDialog in WPF)
    web通过Ajax与WCF交互
    项目管理之我见-程序员程序开发步骤
    存储过程
  • 原文地址:https://www.cnblogs.com/newAndHui/p/13745031.html
Copyright © 2011-2022 走看看