toJSON抛出异常It is illegal to call this method if the current request is not in asynchronous mode
发布时间
阅读量:
阅读量
问题描述
采用AOP的方法实现了日志记录功能,在此过程中,默认调用了JSON对象 toString方法来将joinPoint获取到的参数集合转换为字符串形式,并最终生成了日志信息。然而,在执行过程中遇到了一个问题:导致了一个异常被抛出:Caused by: java.lang.IllegalStateException, 表明当前请求处于同步模式下(即isAsyncStarted()返回false)是不允许调用该方法的。
原因分析及解决方法
原因分析
该错误的主要原因在于,在调用JSON.toJSON()方法进行数据转换时,默认要求输入参数必须具备可序列化的属性;当输入参数不具备此属性时,则会导致该错误。
解决方法
将不符合序列化条件的入参对象剔除,并将所需数据予以保留。对于这里的joinPoint而言,则需要剔除request和response对象。
判断request和response的代码:
//object为遍历出来的参数,逐个判断是否为request或response
if (object instanceof HttpServletRequest
|| object instanceof HttpServletResponse)
{
continue;//跳过处理
}
//否则继续处理
java
完整代码:
//对入参进行遍历
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();
}
}
}
java

全部评论 (0)
还没有任何评论哟~
