Anda di halaman 1dari 1

When Things Go Wrong

Sometimes things go wrong. There are any number of possible causes: bad parameters,missing resources, etc. The point here is that a servlet has to be prepared for problems, both expected and unexpected. There are two points of concern when things go wrong: Limiting damage to the server Properly informing the client Status Codes The simplest way for a servlet to report an error is to use the sendError() method to set the appropriate 400 series or 500 series status code. For example, when the servlet is asked to return a file that does not exist, it can return SC_NOT_FOUND. When it is asked to do something beyond its capabilities, it can return SC_NOT_IMPLEMENTED. And when the entirely unexpected happens, it can return SC_INTERNAL_SERVER_ERROR. By using sendError() to set the status code, a servlet provides the server an opportunity to give the response special treatment. Logging Servlets have the ability to write their actions and their errors to a log file using the log() method: public void ServletContext.log(String msg) public void ServletContext.log(Exception e, String msg) The single-argument method writes the given message to a servlet log, which is usually an event log file. The two-argument version writes the given message and exceptions stack trace to a servlet log. The GenericServlet class also provides a log() method: public void GenericServlet.log(String msg) Example: Report file not found error try { // statements to return file } catch (FileNotFoundException e) { log("Could not find file: " + e.getMessage()); res.sendError(res.SC_NOT_FOUND); } Reporting In addition to logging errors and exceptions for the server administrator, during development its often convenient to print a full description of the problem along with a stack trace. Unfortunately, an exception cannot return its stack trace as a Stringit can only print its stack trace to a PrintStream or PrintWriter. To retrieve a stack trace as a String, we have to jump through a few hoops. We need to let the Exception print to a special PrintWriter built around a ByteArrayOutputStream. That ByteArrayOutputStream can catch the output and convert it to a String. Exceptions There are some types of exceptions a servlet has no choice but to catch itself. A servlet can propagate to its server only those exceptions that subclass IOException, ServletException, or RuntimeException. The service() method of Servlet declares in its throws clause that it throws IOException and ServletException exceptions. The RuntimeException is a special case exception that never needs to be declared in a throws clause.

Anda mungkin juga menyukai