Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 39 ยท Hooks and Lifecycle

Error Handling and Not Found Routes

Handle errors in Fastify: throw and send errors, custom error classes, setErrorHandler, validation errors, onError, setNotFoundHandler and safe 500 responses.

Production APIs fail constantly in small, boring ways: a client sends bad JSON, a record is gone, a database times out. What separates a pleasant API from a painful one is that every failure has a predictable shape and a correct status code, and that internal details never leak out. Fastify gives you one central place for this: the error handler.

This lesson covers how errors enter that handler, how to write your own, how to build an error class that carries its own status code, and how to handle URLs that match no route.

The runnable examples use the stand-in framework from The Fastify Request Lifecycle, not the real package. Its default error body and setErrorHandler behave like Fastify's for the cases shown.

How an error enters the handler

Any of these makes Fastify build an error response instead of running the rest of the lifecycle:

  • an async handler or hook throws (or returns a rejected promise);
  • code calls reply.send(new Error('...')) or reply.send(someErrorObject);
  • validation fails (the error has a validation array in real Fastify);
  • a parser fails (invalid JSON, unsupported media type);
  • no route matches (this goes to the not-found handler, covered below).

The status code comes from error.statusCode (or error.status) if it exists and is 4xx or 5xx, otherwise it is 500. The default body is:

JSON
{ "statusCode": 400, "error": "Bad Request", "message": "body must have required property 'name'" }

That default is already reasonable. Customize it when you want a company-wide error format, translated messages, or to hide the message of 500s.

Errors that carry their status

Instead of scattering reply.code(404).send(...) everywhere, define a small error hierarchy and throw it from anywhere (services, hooks, handlers). The error handler turns it into a response. In real projects the @fastify/sensible plugin provides httpErrors.notFound() and friends; this example writes the same idea by hand.

Node.js Custom error classes and setErrorHandler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the last line: the client sees "Something went wrong", while the log line (which a real app would send to its logger) keeps the real cause. That one rule, log the detail, hide it from the client, prevents a whole class of information leaks (hostnames, SQL, file paths).

Notice also that the handler returns the result of reply.send (it is async). In real Fastify an async error handler must either return reply.send(...) or await it. Writing reply.send(...) without returning in an async function is a classic cause of hanging requests.

What the error handler must never do

  • Throw. If the handler itself throws, Fastify falls back to its default handler for that request. Keep it simple and defensive.
  • Re-send after a send. If a hook already sent a response, the error handler is not meant to produce a second one.
  • Trust error.message for 5xx. Developers write messages for developers.

The onError hook

onError is a hook that runs when an error is about to be handled. It is for side effects only: log, count, report to an error tracker. It cannot change the response, and it runs even if you have a custom error handler. Use setErrorHandler to shape the response and onError to observe it.

JavaScript
// real Fastify
app.addHook('onError', async (request, reply, error) => {
  metrics.increment('http.errors', { status: error.statusCode ?? 500 });
});

Scoped error handlers

Like hooks, setErrorHandler is encapsulated. A plugin can install its own handler for its routes (for example JSON:API errors under /v2, plain errors for /v1) and the rest of the app is unaffected. A handler set on the root instance is inherited by all children that do not set their own.

Node.js Two plugins, two error formats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The root route keeps the default format, /v1/fail returns plain text and /v2/fail returns a JSON:API-like body, all from the same thrown error.

Not found handlers

When no route matches, Fastify answers 404 with this default body:

JSON
{ "message": "Route GET:/nothing not found", "error": "Not Found", "statusCode": 404 }

To customize it, call setNotFoundHandler. In real Fastify it can be scoped with a prefix, so /api/* returns JSON while the rest of the site returns an HTML page:

JavaScript
// real Fastify
app.setNotFoundHandler((request, reply) => {
  reply.code(404).type('text/html').send('<h1>Page not found</h1>');
});

app.register(async (api) => {
  api.setNotFoundHandler((request, reply) => {
    reply.code(404).send({ error: 'unknown endpoint', path: request.url });
  });
}, { prefix: '/api' });

The not-found handler runs through a part of the lifecycle too: onRequest hooks of the root scope run for unmatched URLs, which is handy for logging or blocking scanners. Other hooks (such as preHandler) can be set with the preHandler option of setNotFoundHandler. Also note that a wrong method on an existing path (a POST to a GET-only route) is a 404 in Fastify, not a 405, unless you register a catch-all yourself.

You can send a request to the not-found handler from inside a route with reply.callNotFound(), for example when a record lookup returns nothing and you would like the same 404 format used for unmatched URLs.

Practical rules

  1. Throw errors with statusCode; do not build 4xx bodies by hand in every handler.
  2. One central error handler formats everything; validation errors are 400, unexpected errors are 500.
  3. Log the real error (with request.id), send a generic message for 5xx.
  4. Do not use errors for normal control flow in hot paths: creating an Error captures a stack trace, which is not free.
  5. In tests, assert on statusCode and the error code, not on the human message text.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What status code does Fastify use for a thrown error that has no statusCode property?

    An error without a usable status code is treated as an unexpected failure, so the response is 500 Internal Server Error.
  2. 2. What is the correct role of the onError hook?

    onError observes errors. The response is shaped by setErrorHandler.
  3. 3. In an async error handler, what must you do with reply.send()?

    Async handlers should return reply.send(...) so Fastify knows the reply is finished; forgetting it can leave the request hanging.
  4. 4. A client sends POST to a path that only has a GET route. What does Fastify answer by default?

    The router matches method and path together, so an unsupported method is simply an unmatched route and reaches the not-found handler.
  5. 5. Why should the error handler hide error.message for 5xx errors?

    Internal messages are written for developers and may reveal infrastructure. Log them with the request ID and return a generic text.

Summary

  • Errors come from throws, reply.send(error), validation, parsing and unmatched routes; the status comes from error.statusCode, else 500.
  • Define error classes that carry statusCode and a stable code, then throw them from anywhere.
  • setErrorHandler shapes responses and is encapsulated per plugin; onError is only for side effects.
  • Log details, but send generic messages for 5xx.
  • setNotFoundHandler customizes 404s, and a wrong method on a known path is also a 404.

Next: Response Serialization and Schemas