Lesson 19 / 30

Error Handling

Gracefully handle errors and control error responses.

Error handling strategy

Throw errors in route handlers; Fastify's built-in error handler catches them and returns appropriate status codes and responses.

Custom error class

Define a custom error class to control status codes and payloads.

class AppError extends Error {
  constructor(message, statusCode = 500) {
    super(message);
    this.statusCode = statusCode;
  }
}

fastify.get('/users/:id', async (req) => {
  const user = await findUser(req.params.id);
  if (!user) {
    throw new AppError('User not found', 404);
  }
  return user;
});

fastify.setErrorHandler((err, req, reply) => {
  const statusCode = err.statusCode || 500;
  reply.status(statusCode).send({ error: err.message });
});

Async error handling

Fastify automatically catches errors thrown in async handlers—no need for try/catch wrappers.