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

前端 未结 4 1300
悲&欢浪女
悲&欢浪女 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:15

    Or you can intercept all your exceptions using a servlet:

    
    
        ErrorServlet
        com.domain.MyErrorServlet
        
    
    ErrorServlet
        /error
    
    
        java.lang.Throwable
        /error
    
    

    Then in the servlet you can handle the exception like this

    public class MyErrorServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response){
           Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
           // You can log the exception, send to email, etc
        }
    }
    

提交回复
热议问题