Skip to content
NestPath

Exception Filters

One consistent error shape for every failure. The HttpException hierarchy, catch-all filters, DI-aware registration, custom domain exceptions, and never leaking internals to clients.

Alright, let's talk about what happens when things go wrong — because right now, you're letting NestJS decide what your error responses look like, and that's like letting the framework pick your outfit for a job interview.


The Problem You Have Right Now

When your TasksService throws NotFoundException, NestJS sends this:

json
{
  "statusCode": 404,
  "message": "Task with id 5 not found",
  "error": "Not Found"
}

When ValidationPipe rejects bad input:

json
{
  "statusCode": 400,
  "message": ["title should not be empty", "description must be a string"],
  "error": "Bad Request"
}

Notice the inconsistency? In one, message is a string. In the other, it's an array. Your frontend dev (which is also you) now has to write typeof error.message === 'string' ? [error.message] : error.message on the React side. That's disgusting. And it gets worse — unhandled exceptions return:

json
{
  "statusCode": 500,
  "message": "Internal server error"
}

Three different shapes for three different errors. No timestamp, no request path, no error code your frontend can switch on. You're shipping an API that makes the consumer guess the response format. You've built APIs long enough to know that's unacceptable.


Where Exception Filters Sit in the Lifecycle

Remember this?

Request → Middleware → Guards → Interceptors → Pipes → Controller → Service

exception thrown anywhere along this chain

EXCEPTION FILTER
catches it
HTTP Response (formatted error)

Exception Filters are the safety net at the bottom. Any exception thrown at any stage — middleware, guard, pipe, controller, service — gets caught by the appropriate filter. They're the last thing that touches the response before it goes to the client.

Analogy

An exception filter is the hospital's emergency room. It doesn't matter which floor the patient collapsed on — the kitchen, the lobby, the operating theatre — every emergency ends up at the same ER, where one trained team decides what the outside world is told. Nobody phones the patient's family directly from a random hallway.


NestJS Built-in Exception Hierarchy

Before writing custom filters, understand what NestJS gives you out of the box:

HttpException (base class)
BadRequestException(400)
UnauthorizedException(401)
ForbiddenException(403)
NotFoundException(404)
MethodNotAllowedException(405)
ConflictException(409)
GoneException(410)
PayloadTooLargeException(413)
UnprocessableEntityException(422)
InternalServerErrorException(500)
... more

All of these extend HttpException. When you throw new NotFoundException('...'), NestJS's built-in global exception filter catches it and formats the response. Your custom filter will replace that default behavior.

Analogy

The exception hierarchy is the ER's triage chart: every known condition has a standard code and a standard severity. Because every specific condition ("not found", "forbidden", "conflict") is a variant of the same base diagnosis form, one doctor who knows the base form can treat them all.


Step 1: Define a Consistent Error Response Shape

Before writing any filter code, decide what every error response from your API will look like. This is an API design decision, not a NestJS decision.

src/common/interfaces/error-response.interface.ts

ts
export interface ErrorResponse {
  statusCode: number;
  error: string;
  message: string;
  details?: string[];    // validation errors, multiple issues, etc.
  timestamp: string;
  path: string;
}

Every single error — 400, 401, 404, 500 — same shape. Your frontend always knows: - message is always a single human-readable string - details is always an array (or absent) — never a surprise string - path tells you which endpoint failed - timestamp for debugging and logging

Analogy

This interface is the hospital's standard incident report form. Whether a patient fainted or the building caught fire, the report always has the same boxes in the same places — what happened, where, when, how serious. Anyone reading reports (your frontend) can process a stack of them without deciphering a new format each time.


Step 2: HttpException Filter — Catching Known Errors

What is HTTP exception in depth?

HTTP Exception

An HTTP exception is a programming construct used in web development frameworks to represent an error that occurs during the processing of an HTTP request and results in an HTTP error status code response being sent to the client.


Key Characteristics

Purpose

An intentional mechanism for the server to communicate to the client (e.g., a web browser or API consumer) that something went wrong with their request.

Mechanism

When an HTTP exception is raised in server-side code: - It aborts the normal flow of the program. - It automatically generates an HTTP response. - The response includes a specific status code and relevant error details.

Distinction

An HTTP exception is different from general programming exceptions (e.g., IOException, which may indicate a low-level network issue).

  • General Exception → System or runtime-level error.
  • HTTP Exception → Application or protocol-specific error categorized using standard HTTP status codes.

Error Categories

HTTP exceptions generally fall into two main categories based on the first digit of the status code:

  • 4xx — Client Errors
    The client has sent an invalid, malformed, or unauthorized request.

  • 5xx — Server Errors
    The server encountered an unexpected condition or is temporarily unable to handle a valid request.


Common HTTP Exception Examples

400 — Bad Request

The server cannot process the request because the client sent invalid data or incorrect syntax.

401 — Unauthorized

The client must authenticate itself to receive the requested response.

403 — Forbidden

The client is authenticated but does not have permission to access the resource.

404 — Not Found

The server cannot find the requested resource.

409 — Conflict

The request could not be completed due to a conflict with the current state of the resource.

500 — Internal Server Error

A generic error message indicating the server encountered an unexpected condition it cannot handle.

503 — Service Unavailable

The server is temporarily overloaded or undergoing maintenance and cannot process the request.

This handles every HttpException and its subclasses — the ones you throw intentionally.

src/common/filters/http-exception.filter.ts

ts
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { ErrorResponse } from '../interfaces/error-response.interface';

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

    // exception.getResponse() returns either a string or an object
    // NestJS is inconsistent here — we normalize it
    const exceptionResponse = exception.getResponse();

    let message: string;
    let details: string[] | undefined;

    if (typeof exceptionResponse === 'string') {
      // throw new HttpException('Something failed', 400)
      message = exceptionResponse;
    } else if (typeof exceptionResponse === 'object') {
      const responseObj = exceptionResponse as Record<string, any>;

      // ValidationPipe sends { message: string[] }
      // Other HttpExceptions send { message: string }
      if (Array.isArray(responseObj.message)) {
        message = 'Validation failed';
        details = responseObj.message;
      } else {
        message = responseObj.message || 'Something went wrong';
      }
    }

    const errorResponse: ErrorResponse = {
      statusCode: status,
      error: this.getErrorName(status),
      message,
      ...(details && { details }),
      timestamp: new Date().toISOString(),
      path: request.url,
    };

    response.status(status).json(errorResponse);
  }

  private getErrorName(status: number): string {
    const errorNames: Record<number, string> = {
      400: 'Bad Request',
      401: 'Unauthorized',
      403: 'Forbidden',
      404: 'Not Found',
      409: 'Conflict',
      422: 'Unprocessable Entity',
      429: 'Too Many Requests',
      500: 'Internal Server Error',
    };
    return errorNames[status] || 'Error';
  }
}

Let's break down what's happening:

@Catch(HttpException) — This decorator tells NestJS: "This filter handles HttpException and all its children." NotFoundException, BadRequestException, ForbiddenException — all caught here because they all extend HttpException.

ArgumentsHost — NestJS is platform-agnostic (HTTP, WebSockets, GraphQL). ArgumentsHost is the abstraction. host.switchToHttp() gives you the Express-specific Request and Response objects. If you were using WebSockets, you'd call host.switchToWs() instead.

The normalization logic — This is where you fix NestJS's inconsistent getResponse() behavior. ValidationPipe errors return { message: string[] }. NotFoundException returns { message: string, error: string, statusCode: number }. A raw throw new HttpException('oops', 400) returns just a string. Your filter normalizes all of these into one consistent shape. The framework won't do this for you.


Step 3: All-Exceptions Filter — Catching the Unexpected

The HttpExceptionFilter only catches exceptions that extend HttpException. What about a TypeError? A null reference? A library throwing a random Error? Those blow right past it and NestJS returns a bare 500 with zero useful information.

src/common/filters/all-exceptions.filter.ts

ts
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { ErrorResponse } from '../interfaces/error-response.interface';

@Catch() // no argument = catches EVERYTHING
export class AllExceptionsFilter implements ExceptionFilter {
  private readonly logger = new Logger(AllExceptionsFilter.name);

  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();

    // if it's an HttpException, let the other filter's logic apply
    // but if we're using this as the only filter, handle it here too
    if (exception instanceof HttpException) {
      // delegate to default behavior or handle similarly
      const status = exception.getStatus();
      const exceptionResponse = exception.getResponse();

      let message: string;
      let details: string[] | undefined;

      if (typeof exceptionResponse === 'string') {
        message = exceptionResponse;
      } else {
        const responseObj = exceptionResponse as Record<string, any>;
        if (Array.isArray(responseObj.message)) {
          message = 'Validation failed';
          details = responseObj.message;
        } else {
          message = responseObj.message || 'Something went wrong';
        }
      }

      const errorResponse: ErrorResponse = {
        statusCode: status,
        error: this.getErrorName(status),
        message,
        ...(details && { details }),
        timestamp: new Date().toISOString(),
        path: request.url,
      };

      response.status(status).json(errorResponse);
      return;
    }

    // THIS is where unhandled, unexpected errors land
    // Log the full error — your monitoring needs this
    this.logger.error(
      `Unexpected exception on ${request.method} ${request.url}`,
      exception instanceof Error ? exception.stack : String(exception),
    );

    // NEVER expose internal error details to the client
    const errorResponse: ErrorResponse = {
      statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
      error: 'Internal Server Error',
      message: 'An unexpected error occurred',
      timestamp: new Date().toISOString(),
      path: request.url,
    };

    response.status(HttpStatus.INTERNAL_SERVER_ERROR).json(errorResponse);
  }

  private getErrorName(status: number): string {
    const errorNames: Record<number, string> = {
      400: 'Bad Request',
      401: 'Unauthorized',
      403: 'Forbidden',
      404: 'Not Found',
      409: 'Conflict',
      422: 'Unprocessable Entity',
      429: 'Too Many Requests',
      500: 'Internal Server Error',
    };
    return errorNames[status] || 'Error';
  }
}

Why two filters instead of one?

You can use just AllExceptionsFilter — it handles both. But separating them has advantages:

  • HttpExceptionFilter is your business error handler — things you expect and throw intentionally
  • AllExceptionsFilter is your crash catcher — things that should never happen

In production, you might add different behavior: business errors get logged at warn level, unexpected errors get logged at error level and trigger alerts. Separation of concerns, again.

Practical choice: For most apps, just use AllExceptionsFilter alone. It handles everything. Use two only when your logging/monitoring needs differ between expected and unexpected errors.

Analogy

Two filters is the difference between the routine clinic and the crash team. A patient with a known allergy acting up (an expected business error) gets calm, standard treatment and a note in the chart. A patient who collapses for no known reason (a TypeError) triggers the alarm, the full crash team, and a written investigation — same building, very different response levels.


Step 4: Register the Filter Globally

main.ts — Updated

ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );

  app.useGlobalFilters(new AllExceptionsFilter());

  await app.listen(3000);
}
bootstrap();

Order matters? Not between useGlobalPipes and useGlobalFilters — they operate at different stages. But if you register multiple filters, the last registered catches first. Think of it as a stack. For now with one filter, don't worry about it.


Step 5: DI-Aware Global Filter (The Better Way)

The app.useGlobalFilters(new AllExceptionsFilter()) approach has a limitation — you're manually instantiating the filter. It can't inject dependencies. Need to inject a LoggerService or ConfigService? Can't do it with new.

The DI-aware approach registers the filter through a module:

app.module.ts

ts
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { TasksModule } from './tasks/tasks.module';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';

@Module({
  imports: [TasksModule],
  providers: [
    {
      provide: APP_FILTER,
      useClass: AllExceptionsFilter,
    },
  ],
})
export class AppModule {}

Now the filter is created by NestJS's DI container. You can inject anything into it:

ts
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(
    private readonly configService: ConfigService, // now this works
  ) {}
}

If you use the APP_FILTER approach, remove the app.useGlobalFilters() line from main.ts — don't register it twice.

Analogy

Instantiating the filter yourself with new is hiring an outside contractor: they show up, but they have no staff badge, so they can't requisition anything from the hospital's supply room (the DI container). Registering via APP_FILTER makes the ER team actual hospital employees — now they can request equipment, records, and specialists like everyone else.


Now Let's See It In Action With Your CRUD

Scenario 1: GET /tasks/999 — Task not found

Service throws new NotFoundException('Task with id 999 not found').

json
{
  "statusCode": 404,
  "error": "Not Found",
  "message": "Task with id 999 not found",
  "timestamp": "2026-02-12T10:30:00.000Z",
  "path": "/tasks/999"
}

Scenario 2: POST /tasks with { "title": "", "extra": "hack" } — Validation fails

json
{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "Validation failed",
  "details": [
    "property extra should not exist",
    "title should not be empty — what kind of task has no title?",
    "description should not be empty",
    "description must be a string"
  ],
  "timestamp": "2026-02-12T10:30:00.000Z",
  "path": "/tasks"
}

Scenario 3: GET /tasks/abc — ParseIntPipe fails

json
{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "Validation failed (numeric string is expected)",
  "timestamp": "2026-02-12T10:30:00.000Z",
  "path": "/tasks/abc"
}

Scenario 4: Some random null pointer in your service — Unhandled crash

What the server logs (full stack trace for you):

text
[ERROR] [AllExceptionsFilter] Unexpected exception on GET /tasks
TypeError: Cannot read properties of undefined (reading 'id')
    at TasksService.findOne (tasks.service.ts:15:22)
    ...

What the client gets (sanitized, no internals leaked):

json
{
  "statusCode": 500,
  "error": "Internal Server Error",
  "message": "An unexpected error occurred",
  "timestamp": "2026-02-12T10:30:00.000Z",
  "path": "/tasks"
}

The client never sees your stack trace, file paths, or internal error messages. Server logs everything it needs. That's the split you want.

Analogy

It's the difference between the medical chart and what's said in the waiting room. The chart (your server logs) records everything in clinical detail so the staff can act; the family (the client) hears a calm, careful summary. Reading the raw chart aloud in the waiting room helps nobody and can genuinely cause harm — that's what leaking a stack trace is.


Scope Levels — Where Filters Can Be Applied

You registered globally. But filters can also be scoped:

ts
// Controller level — catches exceptions from all routes in this controller
@Controller('tasks')
@UseFilters(new HttpExceptionFilter())
export class TasksController {}

// Route level — catches exceptions from this one route only
@Get(':id')
@UseFilters(new HttpExceptionFilter())
findOne(@Param('id', ParseIntPipe) id: number) {}

When to scope? When a specific controller or route needs different error formatting than the rest of your API. For example, a webhook controller that needs to return a specific error format that the webhook provider expects. Otherwise, global is the way.

Analogy

A global filter is the hospital's main ER that serves the whole building; a scoped filter is a specialist clinic with its own intake rules for one wing. You only open a separate clinic when that wing genuinely needs different treatment — say, the maternity ward's own protocols. For everything else, sending patients to the one central ER keeps care consistent.


Custom Business Exceptions — Leveling Up

As your app grows, you'll want more specific exceptions than just generic NotFoundException. Create domain-specific ones:

src/common/exceptions/task-not-found.exception.ts

ts
import { NotFoundException } from '@nestjs/common';

export class TaskNotFoundException extends NotFoundException {
  constructor(taskId: number) {
    super(`Task with id ${taskId} not found`);
  }
}

In your service:

ts
findOne(id: number): Task {
  const task = this.tasks.find((t) => t.id === id);
  if (!task) {
    throw new TaskNotFoundException(id); // cleaner, self-documenting
  }
  return task;
}

Same behavior, but now your code reads like intent. TaskNotFoundException extends NotFoundException extends HttpException — your existing filter catches it without any changes. Polymorphism doing what it was built for.

Analogy

A custom exception is a precise diagnosis instead of a vague symptom. "Patient unwell" (generic NotFoundException) gets the job done, but "acute task-not-found, id 999" tells every reader of the chart exactly what happened. And because the precise diagnosis is still filed under the same standard category, the ER handles it with zero new procedures.


Level Up: Machine-Readable Error Codes

Your envelope currently gives the client a human-readable message. That's great for humans — and useless for code. If the frontend wants to react differently to "this task doesn't exist" versus "you sent a duplicate title," it's stuck doing if (message.includes('not found')) — string-matching English, which breaks the moment you reword a message or translate it.

The fix is a stable errorCode — a machine-readable constant the frontend can switch on, independent of the wording. Add one field to your envelope:

ts
export interface ErrorResponse {
  success: false;
  statusCode: number;
  error: string;
  errorCode: string;   // ← stable, machine-readable: 'TASK_NOT_FOUND', 'VALIDATION_FAILED'
  message: string;     // ← human-readable, safe to reword or translate
  details?: string[];
  timestamp: string;
  path: string;
}

Let your custom exceptions carry their own code, and have the filter read it (falling back to a sensible default for anything that doesn't):

ts
// custom exception carries its code
export class TaskNotFoundException extends NotFoundException {
  readonly errorCode = 'TASK_NOT_FOUND';
  constructor(taskId: number) {
    super(`Task with id ${taskId} not found`);
  }
}

// in the filter, when building the response:
const errorCode =
  (exception as any).errorCode ??           // custom exceptions
  (status === 400 ? 'VALIDATION_FAILED' : 'ERROR'); // sensible fallback

Now the frontend does switch (error.errorCode) and never parses a sentence again. statusCode says how it failed at the HTTP level; errorCode says what failed in your domain. You'll rely on this in the capstone, where every error envelope carries one.

Analogy

message is the doctor explaining your condition in plain language; errorCode is the ICD diagnosis code stamped on the chart. The explanation can be reworded for every patient, but the code is the same everywhere — so the insurance system (your frontend) can process it automatically without reading a word of English.


Updated Project Structure

src
app.module.ts
main.ts
common
filters
all-exceptions.filter.ts
http-exception.filter.ts(optional, if splitting)
interfaces
error-response.interface.ts
exceptions
task-not-found.exception.ts(optional, as you grow)
tasks
tasks.module.ts
tasks.controller.ts
tasks.service.ts
dto
create-task.dto.ts
update-task.dto.ts
interfaces
task.interface.ts

Notice the common/ folder. This is where cross-cutting concerns live — filters, guards, interceptors, decorators, pipes. They don't belong to any specific module. They belong to the app.


Recap — What You've Added

text
Before:  Exception → NestJS default handler → inconsistent JSON shape
After:   Exception → Your filter → consistent shape, proper logging, no leaked internals

Your controller and service code? Still untouched. Again. The architecture lets you layer behavior without modifying existing code. That's the pattern you should be noticing by now — every NestJS feature slots into the pipeline without touching what's already there.

Next up when you're ready: Interceptors — transforming successful responses, wrapping them in consistent envelopes, adding timing/logging, and the pre/post execution model.