Netty exceptionCaught 异常机制

本文深入探讨了Netty框架中异常处理的机制,重点讲解了exceptionCaught方法仅捕获入站处理器的异常,而出站异常需通过监听writeAndFlush方法的结果来处理。文章提供了在每个出站处理器中加入try-catch块的建议,并介绍了如何在ExceptionHandler中监听发送操作的结果,以确保消息发送的可靠性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Netty handler的exceptionCaught 只会catch inbound handler的exception, outbound exceptions 需要在writeAndFlush方法里加上listener来监听消息是否发送成功,
最好在每个outbound handler的处理类里加上try catch,只是处理由于程序异常导致的发包失败,由于网络原因没有发送成功,最终会被nettychannel异常检测机制检测到,反馈到channel inactivate事件上,这样能够处理大部分case,但是如果需要保证消息的最终送达,不允许丢失,则需要业务层自己保证。

https://github.com/netty/netty/issues/4721

exceptionCaught(...) is only called for inbound exceptions. All outbound exceptions must by handled in a listener by design. If you always want to have exceptions handled in exceptionCaught(...) just add a ChannelOutboundHandler that will an listener for every outbound operation

Netty outbandHandler write方法抛出的Exception需要加listener监听操作结果,来处理exception,The exceptionCaught() method is only invoked for exceptions from inbound events like channelRead(), channelActive() etc.

参考:

https://github.com/netty/netty/issues/2357

推荐阅读:

https://stackoverflow.com/questions/30994095/how-to-catch-all-exception-in-netty

放在pipline的最后
public class ExceptionHandler extends ChannelDuplexHandler {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        ctx.write(msg, promise.addListener((ChannelFutureListener) future -> {
            if (!future.isSuccess()) {
                logger.error("send data to client exception occur: ", future.cause());
            }
        }));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值