Java6 RuntimeException that returns an Http status code

I found another post that shows how we can create our own checked exceptions that also return an HTTP status code other than 500. However, I need it to be RuntimeException. Then I found WebApplicationException, which is an unchecked exception, returns an HTTP status code, but does not allow me to set the message, as in a regular exception.

Is there any exception thrown in Java EE 6 that allows me to set an error message similar to a regular exception and also returns an HTTP status code that I can set?

Edit: Including an explanation of why I want this at the request of John.

I created a filter to catch HTML and XSS attacks from the parameters of my requests. Instead of checking for it every time in Filter.doFilter, which would be too slow, I expanded HttpServletRequestWrapperand used it like that.

HttpFilterRequest implements Filter
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(new SafeHttpRequest((HttpServletRequest) request), response);
    } catch (SecurityViolationException e) {
        log.warn(format("A security violation was detected. Please enable debug for further details: %s]", e.getMessage()));
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.sendError(e.getStatusCode());
    }response);
  }

SafeHttpRequest extends HttpServletRequestWrapper (supressing parts to shorten code)
  @Override
  public String getParameter(String parameter) {
      return xssAndHtmlValidation(super.getParameter(parameter));
  }
  @Override
  public String getHeader(String name) {
      return xssAndHtmlValidation(super.getHeader(name));
  }

xssAndHtmlValidation()throws SecurityViolationException, which is RuntimeException, but the block catchin doFilterdoes not work, because my exception is thrown as ServletExceptioncontaining SecurityViolationException.

+4
source share
1 answer

, , , SafeHttpRequest.xssAndHtmlValidation() , HttpServletRequest.getParameter() HttpServletRequest.getHeader(), - . , HttpFilterRequest.doFilter(). , , , HTTP.

, . , java.lang.RuntimeException. , , , xssAndHtmlValidation() . , .

catch . , , , , , , getResponseCode(). , catch sendError() , , .

, , , , , sendError() IllegalStateException . ( ), .

, , HTTP. - ? , , , , , .

Update:

, JSP- ServletException, , exception.getCause().getClass() ( null). , .

JSP- - HTTP- 500 , , , . - , . .

, , , , , . , , , , , , /.

+3

Source: https://habr.com/ru/post/1610640/


All Articles