Skip to content

Hook exceptions crash Fastify #1129

@cemremengu

Description

@cemremengu

Not sure if this is a desired behavior (user should handle exceptions instead) but having something like

fastify.addHook('preHandler', (request, reply, next) => {
  throw new Error('test')
})


fastify.addHook('onResponse', (req, res, next) => {
  throw new Error('test')
})

on any hook will crash Fastify. Should it just handle the exceptions and return 500 (or at least log them and not crash) ? I think this can be patched via something like below but maybe there is a better solution

function hookIterator(fn, reply, next) {
  if (reply.res.finished === true) return undefined

  try {
    return fn(reply.request, reply, next)
  } catch (err) {
    reply.sent = false
    reply._isError = true
    reply.send(err)
  }
}
function onResponseIterator(fn, res, next) {
  try {
    return fn(res, next)
  } catch (err) {
    res.log.error({
      res,
      err
    }, 'request errored')
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions