Error Handling In Servlet

by Geethalakshmi 2008-11-27 18:13:12

How do you handle errors in a servlet?


1) return an error code with HttpServletResponse's sendError():

public void sendError(int statuscode)


Some Web servers may look at the error code and generate a response body that explains the error to the client.

2) return a status code with HttpServletResponse's setStatus() and return a response body that explains the error.

3) log the error to the server's log file with ServletContext's log():

public void log(String msg)


For example, if your servlet gets an exception, it should catch it and describe it in your servlet's log file so that you can debug the exception:

try {
// run some code that could cause an exception to be thrown
}
catch (Exception e) {
getServletContext().log("Servlet caught an exception: " + e.getMessage());
}


If your servlet doesn't catch an exception that gets propagated up to the Web server, the Web server may or may not log or report the exception to the client. It depends on the Web server that is running the servlet. In general, it is better to catch all exceptions yourself so that your servlet isn't tied to a particular Web server. i.e., make your servlet portable to other Web servers.

Tagged in:

3175
like
0
dislike
0
mail
flag

You must LOGIN to add comments