0

I have JSP with several the fields one of which is Date, server side as servlets. I have Date check at client side, and i want to make Date check at server side.

I have a method that convert Date from string, which is getted from request.

public static Date convertToDate (String s) throws ParseException {
    return formatter.parse(s);
}

I use this method with try/catch

try {
    Date date = Utils.convertToDate(request.getParameter("Date")));
} catch (ParseException e) {
    //throw what? new Exception or ParseException or something else
    throw new ParseException (request.getParameter("Date")+ "is not a Date");
}

Finally, I handle exception at controller servlet like

    try {
        //some methods that use method convertToDate
    } catch (SomeException e) { //required right exception
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return; 
}

Questions. Should I create new ParseException for adding information or create new exception like IncorrectDateException? Are there more suitable options for handling exception?

Thanks.

Montroz
  • 73
  • 1
  • 2
  • 14

1 Answers1

1

The standard thing to do is have your Servlet's doXxx() method (eg. doGet(), doPost(), etc.) throw a ServletException and allow the container to catch and handle it. You can specify a custom error page to be shown in WEB-INF/web.xml using the tag:

<error-page>
    <error-code>500</error-code>
    <location>/error.jsp</location>
</error-page>

If you end up catching an Exception you can't elegantly handle, just wrap it in a ServletException like this:

try {
    // code that throws an Exception
} catch (Exception e) {
    throw new ServletException(e);
}
constantlearner
  • 5,157
  • 7
  • 42
  • 64
  • Thanks for reply. Is servlet exception suitable for this? I want to make HttpServletResponse.SC_BAD_REQUEST (error code 400), that indicates incorrect client request. – Montroz Nov 22 '13 at 09:20