Skip to content

Using "reply.send()" in async error handler throws "Reply already sent" error #1131

@mixecan

Description

@mixecan

In async route handlers reply.send can be used if no data is returned.
The same does not apply to the error handler function where this situation produces the log "Reply already sent".

const fastify = require('fastify')
const server = fastify({
  logger: { level: "info", }
});

server.setErrorHandler(async (error, request, reply) => {
  reply.code(500).send("A very bad request!");
});

server.get("/bad", {}, async (request, reply) => {
  throw new Error();
});

server.get("/good", {}, async (request, reply) => {
  reply.code(200).send("ok");
  return;
});

server.listen(8000, '0.0.0.0')
  .then()
  .catch(err => {
    console.log(err);
    process.exit(1);
  });
{"level":40,"time":1535983157768,"msg":"Reply already sent","pid":60124,"hostname":"local","reqId":1,"type":"Error","stack":"Error: Reply already sent\n    at _Reply.Reply.send (~/Downloads/tmp/fastify-custom-handler-issue/node_modules/fastify/lib/reply.js:44:23)\n    at result.then.payload (~/Downloads/tmp/fastify-custom-handler-issue/node_modules/fastify/lib/reply.js:310:32)\n    at <anonymous>\n    at runMicrotasksCallback (internal/process/next_tick.js:121:5)\n    at _combinedTickCallback (internal/process/next_tick.js:131:7)\n    at process._tickCallback (internal/process/next_tick.js:180:9)","v":1}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions