Are you referring to request attributes outside of an actual web request

场景

使用spring的时候
报错信息为:
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

分析

简单的说就是没有找到对应的request请求。

此次报错过程是:
controller 里面用Thread执行service,service异常抛出自定义异常,拦截器拦截异常,并打印traceId信息,这个trace工具类,需要request对象。但是找不到所以报错。

这次的错误是因为抛出的异常类型不对。
因为自定义业务异常类型有很多种,如systemException,requestException等,不同的异常,处理方式也不同。 如果抛出requestException,需要从request中获取请求信息,找不到就报错。

没有request对象的常用场景是:
1、controller里面使用普通的Thread线程,这个线程是异步的,并没有request对象。
2、定时任务中也会有同样的问题,因为它不是基于请求的。并没有request对象。

但没有request对象和报错并没有必然联系,我的错误就是抛的自定义异常会经过调用request的拦截器。

解决方案

通用方案:
修改抛出的异常类型为正确的类型。
controller中使用多线程:
如果controller中一定要使用Thread,那么可以用spring那个线程类,能够带request。
定时任务中:
定时任务中没法了,定时没有request,不要抛带request处理的异常即可。

你可能感兴趣的:(spring)