I am writing a servlet, in that if any exception occurs i donэt want to display exception/error message on browser, so I will redirect to my customized error page. So I have done like this:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try{
//Here is all code stuff
}catch(Exception e){
request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
e1.printStackTrace();
}
Is this the correct way, if I am wrong please correct me and if there is any better mechanism please tell me.
One way to handle it in a generic way is to use web.xml like below:
I have just included IO exception but you might have say SQLException you could very well add another error-page and another location for the same. Similarly you could say java.lang.Exception type and one handler handling everything.
Only way to handle it in a generic way is to use
web.xml
like below:The servlet is thrown
ServletException
andIOException
but if you want to handle runtime exceptions and all other exceptions in a single exception handler, you can provide exception-type asThrowable
. You can use multiple error-page entries that will handle different type of exceptions and have different handlers.Example:
In some method, you would have the following: