How to grab uncaught exceptions in a Java servlet web application

别来无恙 提交于 2019-11-30 11:37:05

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

In web.xml (the deployment descriptor) you can use the <error-page> element to specify error pages by exception type or HTTP response status code. For example:

<error-page>
    <error-code>404</error-code>
    <location>/error/404.html</location>
</error-page>
<error-page>
    <exception-type>com.example.PebkacException</exception-type>
    <location>/error/UserError.html</location>
</error-page>

For a NetBeans-centric description, mosey on over to Configuring Web Applications: Mapping Errors to Error Screens (The Java EE 6 Tutorial) (or see the Java EE 5 Tutorial's version).

Not 100% sure if this will work with a servlet container, or how far upstream this call would need to go, but you can call the static setDefaultUncaughtExceptionHandler method on Thread to set a handler that will handle all uncaught exceptions.

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