【Netty源码解读和权威指南】第85篇:Netty异常处理机制——exceptionCaught的正确使用姿势

【Netty源码解读和权威指南】第85篇:Netty异常处理机制——exceptionCaught的正确使用姿势

上一篇【第84篇】Netty Channel注册与Selector源码解析
下一篇【第86篇】Netty HTTP/2支持——多路复用的Web未来


一、异常传播机制

Handler1.channelRead(msg) → 发生异常 ↓ ctx.fireExceptionCaught(cause) ↓ Handler2.exceptionCaught() → 可以处理 ↓ ctx.fireExceptionCaught(cause) Handler3.exceptionCaught() → 可以处理 ↓ ... TailContext.exceptionCaught() → 默认处理 ↓ 打印WARN日志:"An exceptionCaught() event was fired..."

二、正确处理异常

// 在Pipeline末尾添加全局异常HandlerpublicclassGlobalExceptionHandlerextendsChannelInboundHandlerAdapter{@OverridepublicvoidexceptionCaught(ChannelHandlerContextctx,Throwablecause){logger.error("Unhandled exception",cause);if(causeinstanceofIOException){ctx.close();// IO异常,关闭连接}elseif(causeinstanceofDecoderException){// 解码异常,发送错误响应ctx.writeAndFlush(errorResponse);}// 不调用ctx.fireExceptionCaught(cause),终止传播}}// 必须放在Pipeline最后!pipeline.addLast(newGlobalExceptionHandler());

三、常见异常类型

异常场景处理
IOException连接断开close()
DecoderException数据格式错误发送错误响应
TooLongFrameException帧过大close()
ClosedChannelExceptionChannel已关闭忽略

上一篇【第84篇】Netty Channel注册与Selector源码解析
下一篇【第86篇】Netty HTTP/2支持——多路复用的Web未来