title: Can you force a function not to return to the previous stack and just SendRedirect in a Java Servlet?
body: <p>I'm trying to write error handling for a hibernate related project, I'm still new so there should be a better solution than this, but the way I did it was by creating a separate layer for running the hibernate queries
  <br>
  Now when handling hibernate exceptions in that layer I need to somehow sendRedirect without going back to the rest of the code as sendRedirect would throw an exception (forward and include could work but I would rather sendRedirect)
  <br>
  I tried to prevent the rest of the code to know about how I handle exceptions in that layer, but now I wonder if this was a good approach</p>
  <p>Code sample of what I tried but doesn't seem to work as expected</p>
  <pre><code>@WebServlet(&quot;/signup&quot;)
  public class RegistrationController extends HttpServlet {
      @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          String email = request.getParameter(&quot;email&quot;);
          String password = request.getParameter(&quot;password&quot;);
          if (email != null &amp;&amp; password != null) {
              User user = new User(email, hashedPassword);
              UserRepo userRepo = UserRepo.getInstance();
              userRepo.create(user);
              response.sendRedirect(UrlMappingConstants.getInstance().getControllerUrl(PageNames.SIGN_IN_PAGE));
          }
      }
  }
  </code></pre>
  <p>And when something goes wrong in userRepo.create I call this in the catch</p>
  <pre><code>public void handleError() {
      try {
          ThreadLocalContext.forward(ServiceNames.ERROR_REDIRECT);
      } catch (IOException | ServletException ioException) {
          ioException.printStackTrace();
      }
  }
  </code></pre>
  <p>And all that does is redirect to error page</p>
  <pre><code>  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          response.sendRedirect(UrlMappingConstants.getInstance().getControllerUrl(PageNames.TEST_JSP));
      }
  </code></pre>