private static ByteBuf makeChunk(final Context ctx, final MessageSerializer<?> serializer,
                                     final List<Object> aggregate, final boolean hasMore,
                                     final boolean bulking) throws Exception {
        try {
            final ChannelHandlerContext nettyContext = ctx.getChannelHandlerContext();

            ctx.handleDetachment(aggregate);

            if (!hasMore && ctx.getRequestState() == STREAMING) {
                ctx.setRequestState(FINISHING);
            }

            ResponseMessage responseMessage = null;

            // for this state no need to build full ResponseMessage
            if (ctx.getRequestState() != STREAMING) {
                final ResponseMessage.Builder builder = ResponseMessage.build().result(aggregate);

                // need to put status in last message
                if (ctx.getRequestState() == FINISHING) {
                    builder.code(HttpResponseStatus.OK);
                }

                builder.bulked(bulking);

                responseMessage = builder.create();
            }

            switch (ctx.getRequestState()) {
                case NOT_STARTED:
                    if (hasMore) {
                        ctx.setRequestState(STREAMING);
                        return serializer.writeHeader(responseMessage, nettyContext.alloc());
                    }
                    ctx.setRequestState(FINISHED);

                    return serializer.serializeResponseAsBinary(ResponseMessage.build()
                            .result(aggregate)
                            .bulked(bulking)
                            .code(HttpResponseStatus.OK)
                            .create(), nettyContext.alloc());

                case STREAMING:
                    return serializer.writeChunk(aggregate, nettyContext.alloc());
                case FINISHING:
                    ctx.setRequestState(FINISHED);
                    return serializer.writeFooter(responseMessage, nettyContext.alloc());
            }

            return serializer.serializeResponseAsBinary(responseMessage, nettyContext.alloc());

        } catch (Exception ex) {
            final UUID requestId = ctx.getChannelHandlerContext().attr(StateKey.REQUEST_ID).get();
            logger.warn("The result [{}] in the request {} could not be serialized and returned.", aggregate, requestId, ex);
            writeError(ctx, GremlinError.serialization(ex), serializer);
            throw ex;
        }
    }
Check if any exception in the chain is {@link TemporaryException} or {@link Failure} then respond with the
right error code so that the client knows to retry.
gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/handler/HttpGremlinEndpointHandler.java