jettyembedded-jettyjetty-12

How do I handle EofException in Jetty using Servlets?


I'm trying to handle the EofException thrown by Jetty in this servlet, but my own exception handler doesn't work. Instead, the exception is logged to the console and the while loop continues to run (even if I hit ESC on the browser to stop the event stream). Here's the code:

class AppServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            var out = resp.writer;
            resp.setContentType("text/event-stream");
            resp.setCharacterEncoding("UTF-8");
            while(true) {
                try {
                    out.println("Hello, world!\n");
                    out.flush();
                    Thread.sleep(2000);
                } catch (Exception e) {
                    log.trace("Got an exception: {}", e.cause);
                    out.close()
                }
        }
}

}


Solution

  • The HttpServletResponse.getWriter() returns a java.io.PrintWriter instance.

    With the java.io.PrintWriter class specifically, the javadoc points out that there will never be an exception thrown when using it.
    It is your responsibility to call checkError() on that class to find out if it is in error.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/PrintWriter.html