Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 42 ยท The Request Pipeline

Exception Filters and Errors

Learn NestJS error handling: HttpException and the built-in exceptions, writing @Catch filters, binding them globally, and returning one consistent error body.

Things go wrong: a user does not exist, a body is invalid, a database is down. Nest has a built-in exceptions layer that catches every error thrown while handling a request and turns it into an HTTP response. You normally just throw, and Nest does the rest.

Two ideas make this layer useful. First, exceptions such as NotFoundException carry a status code and a message, so throwing one anywhere (a service, a guard, a pipe) produces the right response. Second, exception filters let you take over the last step and decide exactly what the error response looks like, so every endpoint of your API reports problems in the same shape.

Exception filters are the final stage of the pipeline described in Middleware. The Nest code below is read-only, since it needs Node and npm. The runnable parts are stand-ins that reproduce the mapping and the filter lookup in plain JavaScript.

What happens when you throw

Throw In a service, guard or pipe.
Catch Nest finds a matching filter.
Respond The filter writes the response.

No matching filter? The built-in one answers.

1 / 2

Throwing HttpException

HttpException is the base class. It takes a response (a string or an object) and a status code:

TypeScript
import { HttpException, HttpStatus } from '@nestjs/common';

throw new HttpException('This account is suspended', HttpStatus.FORBIDDEN);

The second argument lives in the HttpStatus enum, which gives names to numbers (HttpStatus.FORBIDDEN is 403). An optional third argument carries a cause (the original error, for logging) and a description:

TypeScript
throw new HttpException(
  { statusCode: 403, message: 'Account suspended', code: 'ACCOUNT_SUSPENDED' },
  HttpStatus.FORBIDDEN,
  { cause: originalError },
);

When the first argument is an object, Nest sends that object as the response body, so you control the JSON. When it is a string, Nest builds a body from it. The cause is never sent to the client.

The built-in exceptions

Writing status codes by hand gets tedious, so Nest provides ready-made subclasses with the right status and a default message. A few of the most used:

Exception Status Typical use
BadRequestException 400 Invalid input that a pipe did not catch
UnauthorizedException 401 Missing or invalid credentials
ForbiddenException 403 Known user, not allowed
NotFoundException 404 Missing resource
ConflictException 409 Duplicate email, version conflict
UnprocessableEntityException 422 Well-formed but semantically wrong data
PayloadTooLargeException 413 Body too big
InternalServerErrorException 500 Server bug
ServiceUnavailableException 503 Dependency down
RequestTimeoutException 408 Used by timeout interceptors
TypeScript
const user = await this.users.findById(id);
if (!user) {
  throw new NotFoundException(`User ${id} was not found`);
}

The default response body for that exception contains the status code, your message and the standard reason phrase, for example Not Found. Pipes throw BadRequestException, and the guard examples throw UnauthorizedException, so one mechanism handles errors from every stage.

Anything that is not an HttpException (a TypeError, a failed database call) is unexpected. Nest answers with a generic 500 Internal server error body and does not leak the message to the client. Your real error still needs logging, which is one of the jobs of a custom filter.

Writing a filter with @Catch

A filter is a class that implements ExceptionFilter and is marked with @Catch(). The argument of @Catch lists the exception classes it handles:

TypeScript
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpErrorFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();
    const body = exception.getResponse();

    response.status(status).json({
      statusCode: status,
      message: typeof body === 'string' ? body : (body as any).message,
      path: request.url,
      timestamp: new Date().toISOString(),
    });
  }
}

host is an ArgumentsHost, the parent of the ExecutionContext you used in guards. exception.getStatus() and exception.getResponse() give you the data to build any body you like.

To catch everything, including plain Error objects, use @Catch() with no arguments and check what you got:

TypeScript
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  private readonly logger = new Logger(AllExceptionsFilter.name);

  catch(exception: unknown, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    const isHttp = exception instanceof HttpException;
    const status = isHttp ? exception.getStatus() : 500;

    if (!isHttp) this.logger.error(exception);

    response.status(status).json({
      statusCode: status,
      message: isHttp ? exception.message : 'Internal server error',
    });
  }
}

The important habit is in the last lines: log unexpected errors in full, but send the client only a generic message. Stack traces, SQL and file paths in error bodies are a gift to attackers.

When you want most of the default behavior, extend BaseExceptionFilter from @nestjs/core and override only what you need. When you want a filter that works for both Express and Fastify, inject HttpAdapterHost and call httpAdapter.reply(...) instead of using response.status().json().

Binding filters

TypeScript
@Post()
@UseFilters(HttpErrorFilter)           // one route
create() { /* ... */ }

@Controller('cats')
@UseFilters(HttpErrorFilter)           // one controller
export class CatsController {}

For the whole application, register it in main.ts with app.useGlobalFilters(new AllExceptionsFilter()), or as a provider with the APP_FILTER token when the filter needs injected services:

TypeScript
@Module({
  providers: [{ provide: APP_FILTER, useClass: AllExceptionsFilter }],
})
export class ErrorsModule {}

Unlike guards and interceptors, filters are tried from the most specific to the least: a filter on the route gets the first chance, then the controller, then global ones. The first filter whose @Catch type matches the exception handles it, and the others are skipped. This lets a global catch-all coexist with a specific filter for one controller.

A consistent error body

Clients love predictable errors. Pick one shape and have the global filter produce it for everything, for example:

JSON
{
  "statusCode": 404,
  "error": "Not Found",
  "message": "User 7 was not found",
  "path": "/users/7",
  "timestamp": "2026-01-01T12:00:00.000Z"
}

Include a stable machine-readable code if clients need to react to specific failures, and a request id so a support ticket can be matched to your logs. The validation lesson showed that ValidationPipe produces message as an array, so decide whether your filter keeps arrays or joins them. Document the shape in your OpenAPI file (OpenAPI and Swagger Docs).

Stand-in: exceptions and a global mapper

This is not Nest. It defines a small HttpException family, a mapper that turns any thrown value into a response, and a fixed clock so the output is deterministic. It shows the key rule: HTTP exceptions keep their message, anything else becomes a generic 500 and is logged.

JS Mapping errors to one response shape

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

No output.

The last request threw a TypeError. The client sees only "Internal server error", while the real message ends up in the log list. Without the filter, the three HTTP errors would still produce correct statuses; the filter adds the shared shape.

Stand-in: which filter handles the error?

The second stand-in implements filter lookup by specificity: route, then controller, then global, with @Catch-style type lists. A filter with an empty list catches everything.

JS Filter precedence: route, controller, global

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

No output.

NotFoundException is claimed by the most specific route filter. ConflictException is an HttpException but not a NotFoundException, so it falls to the controller filter. Both DatabaseError and TypeError are plain errors, so only the global catch-all can handle them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A service throws new TypeError('x is undefined') and no custom filter is installed. What does the client receive?

    Only HttpException and its subclasses carry a status and message for the client. Any other error is reported as a generic 500.
  2. 2. What does a filter declared with @Catch() and no arguments handle?

    An empty @Catch() is a catch-all. Check the type inside catch() so you can treat HTTP errors and unexpected errors differently.
  3. 3. A route has its own filter, the controller has another, and a global filter exists. Which one gets the first chance to handle a matching exception?

    Filters are tried from the most specific to the least specific, and the first match handles the error.
  4. 4. Why should a catch-all filter log unexpected errors but not return their message to the client?

    Operators need the full error for debugging, but clients only need to know that something went wrong on the server.

Summary

  • Throw HttpException or a built-in subclass such as NotFoundException, and Nest turns it into a response with the right status.
  • Non-HTTP errors become a generic 500; log them yourself in a filter.
  • A filter is a class with @Catch(...) implementing ExceptionFilter.catch(exception, host); an empty @Catch() catches everything.
  • Bind filters on a route, controller or globally (useGlobalFilters or APP_FILTER); the most specific matching filter wins.
  • Use one global filter to give every error the same, documented JSON shape.

Next, learn how to create providers in more flexible ways in Custom Providers.