onError hook

Runs when an error occurs during request handling, before the error handler responds.

Since Fastify 5 Spec ↗

Syntax

app.addHook('onError', async (request, reply, error) => {})

Parameters

NameTypeRequiredDescription
request FastifyRequest No The request object.
reply FastifyReply No The reply object.
error FastifyError No The error that was thrown.

Returns

void | Promise<void> — For observation only; do not send the response.

Examples

import Fastify from 'fastify';

const app = Fastify({ logger: true });

app.addHook('onError', async (req, _reply, error) => {
  req.log.error({ err: error, url: req.url }, 'request failed');
});

Notes

This hook is for side effects like logging and metrics; it cannot change the response, which is produced by setErrorHandler. It runs before the error handler.