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;
    }

 


免責聲明!

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



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