1. 程式人生 > >Netty exceptionCaught 異常機制

Netty exceptionCaught 異常機制

Netty handler的exceptionCaught 只會catch inbound handler的exception, outbound exceptions 需要在writeAndFlush方法里加上listener來監聽訊息是否傳送成功,
生產級別程式碼,最好在每個outbound handler的處理類里加上try catch,只是處理由於程式異常導致的發包失敗,由於網路原因沒有傳送成功,最終會被nettychannel異常檢測機制檢測到,反饋到channel inactivate事件上,這樣能夠處理大部分case,但是如果需要保證訊息的最終送達,不允許丟失,則需要業務層自己保證,可以參考MQTT協議的Qos機制

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