Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Routes and Handlers

Async Handlers and Error Handling

Handle errors in Fastify: throw from async handlers, set statusCode, write custom error classes, use setErrorHandler, hide internal details and log properly.

Real applications fail in many ways: bad input, missing records, expired tokens, database outages, plain bugs. Fastify's error model is small and pleasant: throw an error from an async handler, and Fastify turns it into an HTTP response. This lesson shows how to throw the right errors, how to centralize the formatting, and how to avoid leaking details you should keep private.

Throwing in async handlers

Because handlers are async, any thrown error (or rejected promise from an await) is caught by Fastify and sent through the error handler. No try/catch is needed in each route.

JavaScript
app.get('/users/:id', async (request) => {
  const user = await db.findUser(request.params.id);   // may reject
  if (!user) {
    const error = new Error('User not found');
    error.statusCode = 404;
    throw error;
  }
  return user;
});

The rules Fastify applies:

  • If the error has a statusCode (or status) between 400 and 599, that becomes the HTTP status.
  • Otherwise the status is 500.
  • The body has the shape { statusCode, error, message }, and often a code field for Fastify's own errors.
  • Errors with status 5xx are logged at error level; 4xx are logged at info.
Node.js Throwing errors from async handlers

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 default 500 response includes the original message. That is convenient in development and risky in production (it may reveal table names, file paths or queries). You will fix it below with a custom error handler.

Custom error classes

Creating errors by hand with statusCode gets repetitive. Define small classes that carry the status and a stable machine-readable code:

JavaScript
class AppError extends Error {
  constructor(message, { statusCode = 500, code = 'APP_ERROR' } = {}) {
    super(message);
    this.name = new.target.name;
    this.statusCode = statusCode;
    this.code = code;
  }
}
class NotFoundError extends AppError {
  constructor(what) { super(`${what} not found`, { statusCode: 404, code: 'NOT_FOUND' }); }
}
class ConflictError extends AppError {
  constructor(message) { super(message, { statusCode: 409, code: 'CONFLICT' }); }
}

Your service code then throws domain errors (throw new NotFoundError('User')) without knowing anything about HTTP, and one handler translates them. The official @fastify/sensible plugin offers ready-made helpers like reply.notFound() and app.httpErrors.notFound(), which is a fine alternative (read-only here).

One place to format errors: setErrorHandler

app.setErrorHandler((error, request, reply) => {...}) replaces the default behavior for the instance and all its children. Inside, decide what the client sees and what goes to the log.

Node.js A custom error handler that hides internals

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 TypeError (a bug) is answered with a generic message and a requestId, while a real developer can find the full error in the logs using that id. Domain errors keep their friendly message.

Always send the same shape for every error. API clients then write one error-parsing function. Many teams follow RFC 9457 "problem details" (type, title, status, detail); the exact format matters less than being consistent.

Errors from validation, hooks and not-found

Everything funnels into the same handler:

  • A failed schema validation produces an error with statusCode: 400 and validation details (next chapter). Your handler can check error.validation to format it specially.
  • An error thrown in a hook (for example authentication) behaves exactly like one thrown in the handler.
  • A request for an unknown route is not an error; it goes to the not-found handler (setNotFoundHandler), which you format yourself.

Per-scope handlers are allowed: a plugin can call setErrorHandler for its own routes (for example an HTML error page for the website part, JSON for /api).

Callbacks and promises in the wild

Wrapping callback-style libraries is the usual source of unhandled errors. Convert them to promises so await can surface their errors:

JavaScript
import { readFile } from 'node:fs/promises';
import { promisify } from 'node:util';

const legacyLookup = promisify(oldCallbackApi.lookup);

app.get('/file', async () => {
  const text = await readFile('./data.txt', 'utf8');  // rejection -> error handler
  return { length: text.length };
});

Avoid these traps:

  • async function with a done callback. Fastify refuses mixing them; pick one style.
  • Floating promises: calling somethingAsync() without await inside a handler. If it rejects later, nobody catches it and Node may terminate the process (unhandled rejection). Await it, or attach .catch() and log.
  • forEach(async ...): it does not wait. Use for...of with await, or await Promise.all(items.map(...)).
  • Swallowing errors with an empty catch. If you catch, either handle it fully or rethrow.
Node.js Floating promises vs awaited promises

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 client received 200 OK even though the background work failed. Sometimes that is intended (fire-and-forget work), but then you must handle the failure explicitly (log it, retry it, put it on a queue).

Process-level safety nets

Some errors happen outside any request: a crash in a timer, a lost database connection. Log them and exit so your supervisor restarts a clean process:

JavaScript
process.on('unhandledRejection', (reason) => {
  app.log.fatal({ err: reason }, 'unhandled rejection');
  process.exit(1);
});

Do not try to "keep going" after an unknown error; the process may be in an inconsistent state.

Common mistakes

  • Returning error objects as normal 200 responses (return { error: '...' }). Use proper status codes.
  • Leaking stack traces and internal messages in 500 responses.
  • Catching every error in every handler instead of using one error handler.
  • Using statusCode values outside 400-599 on errors.
  • Logging the same error twice (once in the handler, once in the error handler).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What status code does Fastify use for a thrown Error with no statusCode?

    Unknown errors are server errors, so the default is 500.
  2. 2. Why customize the error handler for 500 errors?

    The default body includes the message, which can reveal internals. Send a generic message and log the details.
  3. 3. What goes wrong with an un-awaited promise in a handler?

    The handler returns first, so a later rejection escapes Fastify's error handling.
  4. 4. Where is a thrown error in a hook handled?

    Errors from hooks, validation and handlers all flow to setErrorHandler.

Summary

  • Throw from async handlers; Fastify turns errors into responses using statusCode (default 500).
  • Define error classes with statusCode and a stable code; throw them from services.
  • Use setErrorHandler to format every error consistently and hide 5xx internals.
  • Await your promises; never leave floating ones that can reject unseen.
  • Log and exit on process-level failures; keep error bodies in one shape.

Next: JSON Schema Basics