How to grab uncaught exceptions in a Java servlet web application

后端 未结 3 1215
天涯浪人
天涯浪人 2021-01-01 21:15

Is there a standard way to catch uncaught exceptions that happen inside of a java servlet container like tomcat or Jetty? We run a lot of servlets that come from libraries

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 22:08

    I think a custom filter actually works best.

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } catch (Throwable e) {
            doCustomErrorLogging(e);
            if (e instanceof IOException) {
                throw (IOException) e;
            } else if (e instanceof ServletException) {
                throw (ServletException) e;
            } else if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                //This should never be hit
                throw new RuntimeException("Unexpected Exception", e);
            }
        }
    }
    

提交回复
热议问题