How to Properly Handle Exceptions in a JSP/Servlet App?

前端 未结 4 1288
悲&欢浪女
悲&欢浪女 2020-11-28 14:09

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

4条回答
  •  旧巷少年郎
    2020-11-28 14:37

    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 tag:

    
        500
        /error.jsp
    
    

    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);
    }
    

提交回复
热议问题