Search code examples
javaspringhttpspring-mvcspring-boot

Throwing HTTP Status code exception from HandlerInterceptor


I am trying to create a HandlerIntecerptor whose pre-handle has the code structure as follows

    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {

    boolean check = //do something
    if(!check)
    {
        throw new HttpStatusCodeException(HttpStatus.TOO_MANY_REQUESTS); //This line gives cannot be instantiated error.
    }
    return check;
}

but it says class cannot be instantiated. Is there a way to throw an http code exception from inside the preHandle?


Solution

  • The class HttpStatusCodeException is abstract and cannot be instantiated.

    Form the Javadoc:

    public abstract class HttpStatusCodeException

    Use HttpClientErrorException or HttpServerErrorException