DEV Community

Cover image for Error handling — Fastify with TypeScript (part 10/18)
Antonio Tripodi
Antonio Tripodi

Posted on

Error handling — Fastify with TypeScript (part 10/18)

Error handling

Tenth chapter of the "Fastify with TypeScript" series. Good error handling is what separates a robust API from a fragile one. Our API currently produces errors in three different shapes, and one of them leaks information. Let's fix both by handling every error in one place.


What happens by default

Fastify catches everything that is thrown in a hook or a handler and turns it into a response. To see what that response looks like, make a handler fail. In src/users/users.route.ts, add this as the second line of the GET / handler:

    throw new Error('connect ECONNREFUSED db-prod-01:5432 (user "admin")');
Enter fullscreen mode Exit fullscreen mode
curl localhost:3000/api/v1/users
# {"statusCode":500,"error":"Internal Server Error","message":"connect ECONNREFUSED db-prod-01:5432 (user \"admin\")"}
Enter fullscreen mode Exit fullscreen mode

The message of an internal error went straight to the client, host name and user included. Messages like this one are written for the developer who reads the log, and they routinely contain details an attacker would be glad to have. Leave the line where it is for a moment.

A centralized error handler

setErrorHandler replaces the default behavior with a function of ours. We put it in a plugin, wrapped with fastify-plugin so that it applies to the whole application (chapter 8). Create src/plugins/error-handler.ts:

// src/plugins/error-handler.ts
import { STATUS_CODES } from 'node:http';
import fp from 'fastify-plugin';
import type { FastifyError } from 'fastify';

export default fp(async function errorHandlerPlugin(fastify) {
  fastify.setErrorHandler((error: FastifyError, request, reply) => {
    const statusCode = error.statusCode ?? 500;

    // A 5xx is a bug or an outage: log it in full. A 4xx is the client's doing: one line is enough
    if (statusCode >= 500) request.log.error({ err: error }, 'Request failed');
    else request.log.info({ code: error.code, statusCode }, error.message);

    if (error.validation) {
      return reply.code(400).send({
        statusCode: 400,
        error: 'VALIDATION_ERROR',
        message: error.message,
        details: error.validation,
      });
    }

    // Never send the message of a server error to the client: it is in the log.
    // The client gets the standard text for the status code, such as "Internal Server Error"
    const message = statusCode >= 500 ? STATUS_CODES[statusCode] : error.message;

    // An error that carries no status code was not raised on purpose: hide its code as well
    const code = error.statusCode ? error.code : undefined;

    return reply.code(statusCode).send({
      statusCode,
      error: code ?? 'INTERNAL_ERROR',
      message,
    });
  });

  // Unknown URLs get the same shape as every other error
  fastify.setNotFoundHandler((request, reply) => {
    return reply.code(404).send({
      statusCode: 404,
      error: 'ROUTE_NOT_FOUND',
      message: `Route ${request.method} ${request.url} not found`,
    });
  });
}, { name: 'error-handler' });
Enter fullscreen mode Exit fullscreen mode

Register it in src/app.ts. Add the import:

import errorHandler from './plugins/error-handler.ts';
Enter fullscreen mode Exit fullscreen mode

and make it the first plugin registered in buildApp(), above the openapi one:

  // First, so that it handles the errors of everything registered after it
  app.register(errorHandler);
Enter fullscreen mode Exit fullscreen mode

Repeat the request:

curl localhost:3000/api/v1/users
# {"statusCode":500,"error":"INTERNAL_ERROR","message":"Internal Server Error"}
Enter fullscreen mode Exit fullscreen mode

The client learns that something went wrong and nothing else. The full error, stack trace included, is in the server's log, written by request.log.error at the top of the handler. That's the rule for every 5xx: the details are for you, not for the caller.

Remove the throw line from the GET / handler.

The handler does four more things:

  • It logs at the right level. A 5xx is a bug or an outage and is logged as an error, in full. A 4xx is the client's doing (a wrong id, a missing token): it gets one info line, so that real problems aren't buried under a stack trace for every mistyped URL.
  • Validation errors (error.validation is set by Fastify when a schema rejects a request) answer 400 with the list of problems in details.
  • Any other error uses its own statusCode and code if it has them. This is what the next section builds on.
  • setNotFoundHandler covers requests to URLs that don't exist, which are not errors thrown by a route and would otherwise keep Fastify's default shape.

Every error response of the API now has the same three fields: statusCode, a machine-readable error code, and a human-readable message.

Typed errors with @fastify/error

Until now the GET /:id route built its 404 by hand. With a central handler, a route only has to throw the right error.

npm install @fastify/error
Enter fullscreen mode Exit fullscreen mode

createError builds an error class with a stable code, a message template and a status code:

const UserNotFound = createError('USER_NOT_FOUND', 'User %s not found', 404);
Enter fullscreen mode Exit fullscreen mode

throw new UserNotFound(id) produces an error whose statusCode is 404 and whose code is USER_NOT_FOUND, which is exactly what our handler reads.

Update src/users/users.route.ts. This is the complete file:

// src/users/users.route.ts
import { Type } from 'typebox';
import createError from '@fastify/error';
import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox';
import {
  CreateUserBody,
  ListUsersQuery,
  UserParams,
  UserResponse,
  type UserResponseType,
} from './users.schema.ts';

const UserNotFound = createError('USER_NOT_FOUND', 'User %s not found', 404);
const EmailTaken = createError('EMAIL_TAKEN', 'Email %s is already registered', 409);

const userRoutes: FastifyPluginAsyncTypebox = async (fastify) => {
  // Temporary in-memory storage: PostgreSQL replaces it in chapter 13
  const users: UserResponseType[] = [];

  fastify.get('/', {
    schema: {
      tags: ['users'],
      querystring: ListUsersQuery,
      response: { 200: Type.Array(UserResponse) },
    },
  }, async (request) => {
    const { limit = 10 } = request.query; // a number: validated and converted by the schema
    return users.slice(0, limit);
  });

  fastify.get('/:id', {
    schema: {
      tags: ['users'],
      params: UserParams,
      response: { 200: UserResponse },
    },
  }, async (request) => {
    const user = users.find((u) => u.id === request.params.id);
    if (!user) throw new UserNotFound(request.params.id);
    return user;
  });

  fastify.post('/', {
    schema: {
      tags: ['users'],
      body: CreateUserBody,
      response: { 201: UserResponse },
    },
  }, async (request, reply) => {
    // The password is validated but not stored yet: hashing arrives in chapter 12
    const { name, email } = request.body;
    if (users.some((u) => u.email === email)) throw new EmailTaken(email);

    const user: UserResponseType = { id: crypto.randomUUID(), name, email, role: 'user' };
    users.push(user);

    reply.code(201);
    reply.header('Location', `/api/v1/users/${user.id}`);
    return user;
  });
};

export default userRoutes;
Enter fullscreen mode Exit fullscreen mode

What changed:

  • Two error classes are defined at the top. They are constants, created once.
  • GET /:id throws UserNotFound instead of sending a 404 itself. Its response schema no longer needs a 404 entry, and the handler no longer needs reply.
  • POST / refuses an email that is already registered with EmailTaken, a rule we didn't have before.

The ErrorResponse schema from chapter 7 is now unused: delete it from src/users/users.schema.ts. Error responses are produced in one place, so no route has to describe them.

Try it

curl -X POST localhost:3000/api/v1/users \
  -H 'content-type: application/json' \
  -d '{"name":"Grace","email":"grace@example.com","password":"correct-horse"}'

# the same request a second time:
# {"statusCode":409,"error":"EMAIL_TAKEN","message":"Email grace@example.com is already registered"}

curl localhost:3000/api/v1/users/3f2f9c2e-9b0a-4a5c-8d1e-7b6f5a4c3d2e
# {"statusCode":404,"error":"USER_NOT_FOUND","message":"User 3f2f9c2e-9b0a-4a5c-8d1e-7b6f5a4c3d2e not found"}

curl -X POST localhost:3000/api/v1/users \
  -H 'content-type: application/json' \
  -d '{"name":"Grace"}'
# {"statusCode":400,"error":"VALIDATION_ERROR","message":"body must have required property 'email'","details":[...]}

curl localhost:3000/nope
# {"statusCode":404,"error":"ROUTE_NOT_FOUND","message":"Route GET /nope not found"}
Enter fullscreen mode Exit fullscreen mode

Four different failures, one shape. A frontend can switch on error (EMAIL_TAKEN, USER_NOT_FOUND) without parsing English sentences, and the message can be reworded at any time without breaking a client.

One way to raise errors

You may come across @fastify/sensible, a plugin that adds shortcuts such as reply.notFound(). We don't install it: createError already covers every case in this project, and a dependency that only offers a second way to do the same thing is one more package to keep updated and audited. Before adding a package, check whether what you already have does the job.


⬅️ Previous chapter: Hooks and the request lifecycle · ➡️ Next chapter: Decorators

This article is part of the "Fastify with TypeScript" series — chapter 10 of 18.

Top comments (0)