app.setErrorHandler()

Defines a custom handler for errors thrown during request processing.

Since Fastify 5 Spec ↗

Syntax

app.setErrorHandler((error, request, reply) => any)

Parameters

NameTypeRequiredDescription
handler Function No Receives the error, request, and reply.

Returns

FastifyInstance — The instance, for chaining.

Examples

import Fastify from 'fastify';

const app = Fastify();

app.setErrorHandler((error, req, reply) => {
  req.log.error(error);
  const status = error.statusCode ?? 500;
  reply.code(status).send({
    error: status >= 500 ? 'Internal Server Error' : error.message,
  });
});

Notes

The handler also receives Fastify validation errors (which carry a `validation` array and statusCode 400). Set per-encapsulation handlers in plugins for scoped error formatting.