### Question:
MessageToMessageEncoder extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { CodecOutputList out = null; try { if (acceptOutboundMessage(msg)) { out = CodecOutputList.newInstance(); @SuppressWarnings("unchecked") I cast = (I) msg; try { encode(ctx, cast, out); } finally { ReferenceCountUtil.release(cast); } if (out.isEmpty()) { out.recycle(); out = null; throw new EncoderException( StringUtil.simpleClassName(this) + " must produce at least one message."); } } else { ctx.write(msg, promise); } } catch (EncoderException e) { throw e; } catch (Throwable t) { throw new EncoderException(t); } finally { if (out != null) { final int sizeMinusOne = out.size() - 1; if (sizeMinusOne == 0) { ctx.write(out.getUnsafe(0), promise); } else if (sizeMinusOne > 0) { if (promise == ctx.voidPromise()) { writeVoidPromise(ctx, out); } else { writePromiseCombiner(ctx, out, promise); } } out.recycle(); } } } protected  MessageToMessageEncoder(); protected  MessageToMessageEncoder(Class<? extends I> outboundMessageType); boolean acceptOutboundMessage(Object msg); @Override void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise);  }### Answer:
@Test public void testIntermediateWriteFailures() { ChannelHandler encoder = new MessageToMessageEncoder<Object>() { @Override protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) { out.add(new Object()); out.add(msg); } }; final Exception firstWriteException = new Exception(); ChannelHandler writeThrower = new ChannelOutboundHandlerAdapter() { private boolean firstWritten; @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (firstWritten) { ctx.write(msg, promise); } else { firstWritten = true; promise.setFailure(firstWriteException); } } }; EmbeddedChannel channel = new EmbeddedChannel(writeThrower, encoder); Object msg = new Object(); ChannelFuture write = channel.writeAndFlush(msg); assertSame(firstWriteException, write.cause()); assertSame(msg, channel.readOutbound()); assertFalse(channel.finish()); }