It is illegal to call this method if the current request is not in asynchronous mode


nested exception is java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)] with root cause

MethodSignature methodSignature = ((MethodSignature) joinPoint.getSignature());
String methodName = methodSignature.getName();
String className = methodSignature.getDeclaringTypeName();
Object[] args = joinPoint.getArgs();


String argwStr = JSON.toJSONString(args);

當使用切面時,如果使用args中包含了,request對象會到導致程序拋出throwable異常信息,所以加切面時建議將args數組中的內容進行移除。或者不要直接將前台的請求進行攔截后進行json轉換。

解決辦法:

public Object businessLog(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature methodSignature = ((MethodSignature) joinPoint.getSignature());
String methodName = methodSignature.getName();
String className = methodSignature.getDeclaringTypeName();
Object[] args = joinPoint.getArgs();
//序列化時過濾掉request和response
List<Object> logArgs = StreamUtil.streamOf(args)
.filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)))
.collect(Collectors.toList());
String argStr = JSON.toJSONString(logArgs);
Object result;

try {
result = joinPoint.proceed();
String resultStr = JSON.toJSONString(result);
//對入參出參做操作
} catch (Exception e) {

StackTraceElement[] stackTraceArray = e.getStackTrace();
byte[] bytesArray = new byte[]{};
for (int i = 0; i < stackTraceArray.length; i++) {
byte[] bytes = stackTraceArray[i].toString().getBytes();
bytesArray = Bytes.concat(bytesArray, bytes);
}
bytesArray = Bytes.concat(("*exception*" + e.getMessage() + "*exception*").getBytes(), bytesArray);
//對異常信息做操作
throw e;
}
return result;
}


public static <T> Stream<T> streamOf(T[] array) {
return ArrayUtils.isEmpty(array) ? Stream.empty() : Arrays.asList(array).stream();
}

Object[] args = joinPoint.getArgs();
Object[] arguments = new Object[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
//ServletRequest不能序列化,從入參里排除,否則報異常:java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
//ServletResponse不能序列化 從入參里排除,否則報異常:java.lang.IllegalStateException: getOutputStream() has already been called for this response
continue;
}
arguments[i] = args[i];
}
String paramter = "";
if (arguments != null) {
try {
paramter = JSONObject.toJSONString(arguments);
} catch (Exception e) {
paramter = arguments.toString();
}
}


免責聲明!

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



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