如何在通用異常處理時獲取到方法名稱(獲取注解參數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里面獲取到方法名稱;

 

 完美!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM