Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an UncaughtExceptionHandler in Servlets

I implemented an UncaughtExceptionHandler on StartUp of tomcat:

 Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            LOGGER.error("Uncaught Exception");
            }
    });

When I produce an Exception in a Servlet it is not caught by my Handler:

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    int i = 1/0;

The console says:

Feb 13, 2014 8:23:58 AM org.apache.catalina.core.StandardWrapperValve invoke Schwerwiegend: Servlet.service() for servlet [ConnectGatewaysServlet] in context with path [/infraview] threw exception java.lang.ArithmeticException: / by zero at net.test.gateway.ConnectGatewaysServlet.doPost(ConnectGatewaysServlet.java:73) at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

How do I implement an UncaughtExceptionHandler for Servlets?

like image 721
Felix Schmidt Avatar asked Jan 24 '26 13:01

Felix Schmidt


1 Answers

That's normal. Tomcat has more than a hundred threads, and the uncaught exception handlers are associated to a given thread (it's coming from the time of ThreadGroups).

What you can do is to wrap the contents of the doPost() in a try-catch block.

The other way is to define error handling in the web.xml - you can also create a servlet for handling errors in other servlets :-) See an example here.

like image 95
rlegendi Avatar answered Jan 26 '26 02:01

rlegendi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!