Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid IllegalStateException when referring to request attributes outside of an actual web request

I am working on a solution that should do something if i am in the middle of a web request or something else if not.

What i am doing is

@Autowired private HttpServletRequest request;

And then trying to access a variable:

request.getRequestURI()

But i am getting java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request...

I would like to avoid the exception and somehow ask the HttpServletRequest weather or not i am in a web request or not.

Is there any way to do it?

Example: Additional info:

@Override
public void trace(String msg) { 
    if (loggerFactory.isRegisteredUrl(request.getRequestURI())){
        loggerFactory.getCustomeLogger(request.getRequestURI()).trace(msg);
        return;
    }
    nativelogger.trace(msg);
}
like image 866
Gleeb Avatar asked Jan 31 '26 00:01

Gleeb


1 Answers

You should probably (not tested) use RequestContextHolder.getRequestAttributes():

Return the RequestAttributes currently bound to the thread.

Returns: the RequestAttributes currently bound to the thread, or null if none bound

So, if the method returns null, the current thread is not handling a request. If it returns a non-null value, it is handling one.

like image 191
JB Nizet Avatar answered Feb 01 '26 15:02

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!