onError hook
Runs when an error occurs during request handling, before the error handler responds.
Syntax
app.addHook('onError', async (request, reply, error) => {}) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
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.