概述
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());
}
}));
}
}
最后
以上就是完美仙人掌为你收集整理的Netty exceptionCaught 异常机制的全部内容,希望文章能够帮你解决Netty exceptionCaught 异常机制所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复