Best practice error handling in JSP Servlets

2020-07-14 10:35发布

问题:

I have a pretty simple web app using jsp/servlets over an Oracle database. The app only has a handful of pages right now, though it is growing.

As of now, I dont have anything that shows users errors. For example, if the database connection fails, the page is just blank. I'm curious what the best practices are error handling? Should I print out a stack trace? Should all errors goto a default error page?

Any advice or reference material would be appreciated. As you might tell, this is kind of new to me.

Thanks

回答1:

For errors that are considered to be unrecoverable (such as database connectivity problems), these sorts of errors are typically caught at the top-most level within the application and dealt with in a single place. Many frameworks will convert these to unchecked exeptions to avoid intermediate layers having to deal with them.

For these unrecoverable exceptions, typically you'd display a user-friendly and fairly generic error page to the user and send a stacktrace (with more detailed information) to a log file - for interrogation by system administrators and/or developers.

The servlet spec provides a way to handle errors through the web.xml via the error-page tag.

If you're using Servlet 3.0 or above, then in your web.xml you can add:

<error-page>
    <location>/error.html</location>
</error-page>

That will catch all unhandled exceptions and send them to the error.html page in the root of the webapp.

In earlier versions of the servlet spec you had to specify the exception type or error code (which you can still do for finer grained error handling):

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/error.html</location>
</error-page>

Or:

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

And:

<error-page>
    <error-code>404</error-code>
    <location>/notFound.html</location>
</error-page>

Plus you can forward to another JSP (or another servlet) if you need to do dynamic processing in the error page:

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

If you need to access the exception from inside your error page (perhaps you want to display some specific data held by the exception - such as a code) then you can access the original exception through the javax.servlet.error.exception request attribute:

Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");

If your app is growing, you may be best to move to an MVC framework - such as Spring MVC - which will make building your app more manageable - plus it will provide consistent and well defined mechanisms for error handling.