Java 后期处理通用异常

发布时间 2023-12-11 20:41:38作者: talentzemin

注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface MyAction {
    String name();
}

使用注解

@MyAction(name = "Navigate to xxx page")
public XXX navigateToUserCenterPage()  {
    
}

通过注解获取出异常的方法信息

public static String getErrorMessageFromMethodAnnotations(Exception exception) {
    List<Method> methods = getCallStackMethods(exception);
    List<String> messageList = new ArrayList<>();
    for (Method method : methods) {
        if (!Proxy.isProxyClass(method.getDeclaringClass())) {
            return extractTestActionMessage(messageList, method);
        }
    }
}

private static List<Method> getCallStackMethods(Exception exception) {
    List<Method> methods = new ArrayList<>();

    if (null == exception) {

        return methods;
    }

    StackTraceElement[] stackTraces = exception.getStackTrace();
    if (ArrayUtils.isEmpty(stackTraces)) {

        return methods;
    }


    StackTraceElement stackTrace;
    for (int i = stackTraces.length - 1; i >= 0; i--) {
        stackTrace = stackTraces[i];

        Class<?> clazz;
        try {
            String className = stackTrace.getClassName();
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            continue;
        }

        Method[] classMethods;
        try {
            classMethods = clazz.getDeclaredMethods();
        } catch (SecurityException e) {
            continue;
        }

        String methodName = stackTrace.getMethodName();
        Method method = Arrays.stream(classMethods)
                .filter(m -> m.getName().equals(methodName))
                .findFirst()
                .orElse(null);
        if (null == method) {
            continue;
        }
        methods.add(method);
    }

    return methods;
}

private static void extractMyActionMessage(List<String> messageList, Method method) {
    TestAction testAction = MethodUtils.getAnnotation(method, MyAction.class, true, true);
    if (testAction != null) {
        String nameValue = testAction.name();
        if (StringUtils.isNotBlank(nameValue)) {
            messageList.add(nameValue.trim() + SPACE + FAILED);
        }
    }
}