AOP拦截日志类,抛异常:java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode

AOP的日志拦截类中,抛出异常:

java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode

主要原因:对方法的参数使用JSON.toJSONString(args[index])转换时,有异常抛出【如果参数类型是请求和响应的http,使用JSON.toJSONString()转换会抛异常】

解决方案:将不能进行序列化的入参过滤掉,只要留下我们需要记录的入参参数记录到日志中即可

完整代码:

/**
     * 从切点中解析出该切点对应的方法
     * @param point point
     * @throws ClassNotFoundException
     * @throws IOException
     * @author 洪墨水
     */
    private void getRequestParams(ProceedingJoinPoint point,
            RecordMessage recordMessage)
            throws ClassNotFoundException, IOException
    {
        /* 类名 */
        String targetObject = point.getTarget().getClass().getName();
        /* 方法名 */
        String methodName = point.getSignature().getName();

        recordMessage.setTargetObject(targetObject);
        recordMessage.setMethod(methodName);

        Object[] args = point.getArgs();

        Class<?> targetClass = Class.forName(targetObject);

        Method[] methods = targetClass.getMethods();

        StringBuilder requestBuilder = new StringBuilder(0);

        /**
         * 遍历方法 获取能与方法名相同且请求参数个数也相同的方法
         */
        for (Method method : methods)
        {
            if (!method.getName().equals(methodName))
            {
                continue;
            }

            Class<?>[] classes = method.getParameterTypes();

            if (classes.length != args.length)
            {
                continue;
            }

            for (int index = 0; index < classes.length; index++)
            {
                // 如果参数类型是请求和响应的http,则不需要拼接【这两个参数,使用JSON.toJSONString()转换会抛异常】
                if (args[index] instanceof HttpServletRequest
                        || args[index] instanceof HttpServletResponse)
                {
                    continue;
                }
                requestBuilder.append(args[index] == null ? ""
                        : JSON.toJSONString(args[index]));
            }

            recordMessage.setRequestParames(requestBuilder.toString());
        }

        return;
    }
原文地址:https://www.cnblogs.com/hongmoshui/p/10938559.html