zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    如何卸载Mysql
    netty4.1.32 pipeline的添加顺序和执行顺序
    protobuf 在win10系统如何编译jar包
    java swing 的各种布局layout
    一些大神的代码功底方面的文章
    图解ByteBuffer
    Eclipse 高亮显示选中的相同变量
    Java synchronized详解(java 线程同步)
    一篇非常全面的 《单例模式》 的讲解的文章
    java中ThreadLocalRandom类和Random类的使用
  • 原文地址:https://www.cnblogs.com/hongmoshui/p/10938559.html
Copyright © 2011-2022 走看看