title: How do I handle error states in servlet filters without showing the user a stack trace?
body: <p>I'm working on a Jetty/RESTEasy app. If I throw a <code>WebApplicationException(myResponse)</code> from one of my REST endpoints, it sends the given response to the client.</p>
  
  <p>When a filter detects an error, I want the same behavior: </p>
  
  <ol>
  <li>It should stop execution from proceeding, and </li>
  <li>It should give the user a clear, JSON-formatted error that does not include a stack trace.</li>
  </ol>
  
  <p>Obviously, just writing to the response stream and <code>return</code>ing works from within the <code>doFilter</code> method. But this doesn't work for other methods called by <code>doFilter</code>.</p>
  
  <p>Throwing any exception will meet condition #1 but I haven't figured out a sane way to meet condition #2 then. (You can see my best attempt at the bottom.)</p>
  
  <p>As Perception explained in his answer, <code>WebApplicationException</code>s are treated like any other exception in the context of a Filter, and therefore give the user a nice ugly stack trace.</p>
  
  <p>So, to sum up my questions:</p>
  
  <ul>
  <li>Do serveltt containers have any equivalent to <code>throw new WebApplicationException(Response)</code>? </li>
  <li>And perhaps more importantly, how do other java projects handle this?</li>
  </ul>
  
  <p>I have this code in one filter and it works, but I'd prefer a more elegant solution that automatically applies to all filters:</p>
  
  <pre><code>public void doFilter(final ServletRequest   request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
      try {
          doFilterOrThrow(request, response, chain);
      } catch (WebApplicationException e) {
          Response res = e.getResponse();
          ((HttpServletResponse) response).sendError(res.getStatus(), (String) res.getEntity());
      }
  }
  </code></pre>