toJSON抛出异常It is illegal to call this method if the current request is not in asynchronous mode

问题描述

在使用AOP实现日志记录功能时,用到了JSON.toJSON()将joinPoint.getArgs()数据转换为Json串,运行时抛出异常Caused by: java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)

原因分析及解决方法

原因分析

抛出该异常的主要原因是JSON.toJSON()转换数据时要求入参必须是能够进行序列化的数据,如果入参不能序列化,则会抛出上述异常。

解决方法

将不能进行序列化的入参对象过滤掉,只要留下我们所需数据即可。对于这里的joinPoint,我们只需要去除request和response对象即可

判断request和response的代码:

//object为遍历出来的参数,逐个判断是否为request或response
if (object instanceof HttpServletRequest
    || object instanceof HttpServletResponse)
{
      continue;//跳过处理
}
//否则继续处理

完整代码:

//对入参进行遍历
for (Object o : paramsArray)
            {
                if (o != null)
                {
                    try
                    {
                        /**
                         * 如果参数类型是请求和响应的http,则不需要拼接;因为这两个参数,使用JSON.toJSONString()转换会抛异常
                         * “It is illegal to call this method if the current request is not in asynchronous mode”
                         */
                        if (o instanceof HttpServletRequest
                                || o instanceof HttpServletResponse)
                        {
                            continue;//跳过拼接
                        }
                        //需要拼接
                        Object jsonObj = JSON.toJSON(o);
                        params += jsonObj.toString() + " ";
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值