Friday, August 04, 2006

Development time Exception handling in a HTTPServlet

I find that a servlet is usually the best/fastest/least_config way to try out things on a j2ee server. So, I tend to write all my Proof of Concept level code in a servlet.

So, what's the best way of checking out what exceptions occur? Even though we could log them and view it via the traditional log method, I prefer dumping the trace onto the screen as well.

So, here's a little utility code that does it for you...

private void dump_log_on_output(Exception e, Writer writer) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream err = new PrintStream(baos);
e.printStackTrace(err);
String trace = baos.toString();
try {
baos.close();
writer.write("\n" + e.toString() + trace);
writer.close();
return;
} catch (IOException ioe) {
ioe.printStackTrace();//hoping this goes to the logs or server shell
} finally {
writer.close();
}
}


And you call it like so:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
/*logic and other yada, yada */
} catch (Exception e) {
// Caveat:: You better not have wasted the response Writer already!!!
dump_log_on_output(e, response.getWriter());

}
}


Now, happy hacking...

Aloha world

In traditional coding style this is a Hello World post.

print("Aloha world")