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的代码:

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

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//对入参进行遍历
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();
}
}
}