Java – how to correctly handle exceptions in JSP / servlet applications?
How to correctly handle errors encountered in servlets? Now, the application I inherited (using only pure jsp / servlet) has a superclass called controller, which extends httpservlet from which all other servlets extend In the controller class, there is a try and catch block, as shown below:
try { // execute doPost or doGet here } catch (Exception e) { // show a generic error page }
Is this the right thing to do? It looks heavy and doesn't always seem to work I'm just an intern, so I don't have much experience Any suggestions? I'm trying to make the application powerful
Solution
The standard practice is to let your servlet's doxxx () method (such as doget(), dopost(), etc.) throw a ServletException and allow the container to capture and process it You can use < error page > to specify what to do in WEB-INF / Web Custom error page displayed in XML label:
<error-page> <error-code>500</error-code> <location>/error.jsp</location> </error-page>
If you finally catch an exception, you can't handle it gracefully. Just wrap it in such a ServletException:
try { // code that throws an Exception } catch (Exception e) { throw new ServletException(e); }