Saturday, November 9, 2013

Gotcha: Error handling in JSP

Struggled a lot with error handling in JSP (yeah, JSP is not my first choice).

The problem I've encountered: if an exception occurs directly in some JSP tag then:
  •  the rendered HTML appear broken at some random point
  •  the error message bypasses the application log and ends up in application server's log (localhost.log in case of Tomcat)
Example problem in JSP:

<%@ page pageEncoding="UTF-8" contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<!-- some amount of markup here -->

<fmt:formatNumber value="100" type="currency" currencyCode="${myMissingAttribute}"/>

<!-- some more markup -->


What I've found while investigating:
  1. JSP default buffer is 8k and auto flush is on. That means after rendering of each 8k chunk the result is sent back to browser. And if your error occurs later in the JSP, browser will end up with incomplete HTML.
  2. To avoid having broken HTML, you should set up big enough buffer for each page and switch auto flush off, for example: <%@ page buffer="512kb" autoFlush="false" %>
  3. And last but not least in the JSP misery list: <jsp:include> fails silently when the page path is incorrect, no errors whatsoever in ANY log !

No comments: