如何正确处理 JSP/Servlet 应用程序中的异常? [英] How to Properly Handle Exceptions in a JSP/Servlet App?

查看:25
本文介绍了如何正确处理 JSP/Servlet 应用程序中的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何正确处理 servlet 中遇到的错误?现在,我继承的应用程序(仅使用普通的 JSP/Servlet)有一个名为 Controller 的超类,它扩展了 HttpServlet 并且所有其他 servlet 都从它扩展而来.在那个 Controller 类中是一个 try 和 catch 块,如下所示:

How do you properly handle errors encountered in a servlet? Right now, the app that I inherited (uses only plain JSP/Servlet) has a superclass called Controller which extends HttpServlet and which all other servlets extend from. In that Controller class is a try and catch block like the following:

try {
    // execute doPost or doGet here
} catch (Exception e) {
    // show a generic error page
}

这是正确的做法吗?它看起来很笨重,似乎并不总是有效.我只是一个实习生,所以我没有很多这方面的经验.有什么建议吗?我正在努力使应用程序更加强大..

Is this the proper way of doing it? It seems clunky and doesn't seem to always work. I'm only an intern so I don't have a lot of experience with this. Any advice? I'm trying to make the app for robust..

推荐答案

标准的做法是让你的 Servlet 的 doXxx() 方法(例如 doGet()doPost() 等)抛出一个 ServletException 并允许容器捕获并处理它.您可以使用 标记指定要在 WEB-INF/web.xml 中显示的自定义错误页面:

The standard thing to do is have your Servlet's doXxx() method (eg. doGet(), doPost(), etc.) throw a ServletException and allow the container to catch and handle it. You can specify a custom error page to be shown in WEB-INF/web.xml using the <error-page> tag:

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

如果你最终捕捉到一个你无法优雅处理的 Exception,只需将它包装在一个 ServletException 中,如下所示:

If you end up catching an Exception you can't elegantly handle, just wrap it in a ServletException like this:

try {
    // code that throws an Exception
} catch (Exception e) {
    throw new ServletException(e);
}

这篇关于如何正确处理 JSP/Servlet 应用程序中的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆