Best practice error handling in JSP Servlets

梦想与她 提交于 2019-12-06 03:36:30

问题


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.



来源:https://stackoverflow.com/questions/20383185/best-practice-error-handling-in-jsp-servlets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!