Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Netty 4, how do I catch all handlers' unprocessed exceptionCaught?

Tags:

netty

In my channel pipeline, there are many handlers.

As I understand, if I don't override their exceptionCaught(ChannelHandlerContext ctx, Throwable cause) method, the default behavior is the cause will be thrown out to the pipeline, and something like this will be logged at WARN level by the pipeline:

An exception was thrown by a user handler's exceptionCaught() method while handling the following exception: ...

I want to override the above pipeline behavior to add some specific logic (ex: if the cause is java.io.IOException: Connection reset by peer, do not log anything to avoid too many "not very useful" log at WARN level).

What should I do?

After some investigation, I found this source code: https://github.com/netty/netty/blob/4.0/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java

private void invokeExceptionCaught(final Throwable cause) {
    try {
        handler.exceptionCaught(this, cause);
    } catch (Throwable t) {
        if (logger.isWarnEnabled()) {
            logger.warn(
                    "An exception was thrown by a user handler's " +
                    "exceptionCaught() method while handling the following exception:", cause);
        }
    }
}

Because it's private, I don't think I can easily override it without using reflection. Is there a better way?

like image 649
Ngoc Dao Avatar asked Feb 15 '23 02:02

Ngoc Dao


2 Answers

You could do this by define a ExceptionHandler then put this handler at the tail of pipeline.

ChannelPipeline p = ch.pipeline();
p.addLast("business", new SomeBusinessHandler());
p.addLast...
p.addLast("exception", new ExceptionHandler());//Make sure this is the last line when init the pipeline.

And code your specific logic within the exceptionCaught method. But never rethrow the exception because this is the end of pipeline.

like image 169
Michael Avatar answered Apr 06 '23 07:04

Michael


Not sure why your exceptionCaught method would throw an exception... I think you just want to override the ChannelHandler.exceptionCaught(..) method and handle it there.

like image 21
Norman Maurer Avatar answered Apr 06 '23 07:04

Norman Maurer