I have a small application using JSPs and servlets for demonstration purposes and currently have code like this to handle exceptions thrown by DAOs and for validation of parameters from requests:
// Get ID from request.
int id = 0;
try {
id = Integer.parseInt(request.getParameter("id"));
}
catch (NumberFormatException e) {
messages.addMessage(e.getMessage());
request.setAttribute("messages", messages.getMessages());
response.sendRedirect("/jsp/exceptions/error500.jsp");
}
// Check person exists.
PersonDAOImpl personDAO = new PersonDAOImpl();
Person person = null;
try {
person = personDAO.get(id);
}
catch (DAOException e) {
messages.addMessage(e.getMessage());
request.setAttribute("messages", messages.getMessages());
response.sendRedirect("/jsp/exceptions/error500.jsp");
}
So when an exception is thrown it can be caught in the servlet and displayed on a general error page. The messages object is simply an instance of a Messages utility class which stores a number of messages in an arraylist.
But what I am puzzled about is how best to remove the clutter caused in the servlets by exception handling code like this:
messages.addMessage(e.getMessage());
request.setAttribute("messages", messages.getMessages());
response.sendRedirect("/jsp/exceptions/error500.jsp");
Any ideas?
Simple validation messages are currently treated differently. If messages need to be displayed to a user e.g. if a numeric parameter to a servlet is out of range, the messages are written to a Messages object. This object is then written to the JSP where the messages can be displayed using JSTL tags. But a generic exception could be used here.
My main aim is to try to keep this simple without going 'overboard' because this application is only a demonstration., e.g. it doesn't matter if stacktrace text is displayed on a page or not.