NestJS course ยท Module 2: Routing and Request Lifecycle

Exception Filters - courts and tribunals of the empire

7 min read ยท
In this lesson6

A provincial asks about a tribute that is not in the register, and the server answers with status 500 and the message "Internal server error". The client cannot tell whether it made a mistake or the database went down, and you do not know what you actually sent. Praetor Augustus, the highest judge of Rome, keeps repeating that every case must reach the right tribunal and end with a clear verdict. In NestJS those tribunals are exception filters - classes that catch exceptions and turn them into HTTP responses.

What are Exception Filters?

In the Roman Empire every kind of case had its own tribunal:

  • Praetorian tribunal - civil cases (404 Not Found)
  • Censor's court - access control (403 Forbidden)
  • Military tribunal - serious violations (500 Internal Error)

NestJS has a built-in exceptions layer that acts as the default tribunal: it catches every unhandled exception. You write your own filter when you want to change the wording of the verdict.

Built-in NestJS exceptions

Before you build your own court, get to know the ready-made verdicts. All the classes below extend HttpException and set the right status code on their own:

import {
  BadRequestException,      // 400
  UnauthorizedException,     // 401
  ForbiddenException,        // 403
  NotFoundException,         // 404
  ConflictException,         // 409
  InternalServerErrorException, // 500
  HttpException,             // base HTTP exception
} from '@nestjs/common';

The comments next to the imports give the code the client will receive. Now we throw these exceptions in the tribute controller:

@Controller('tributa')
export class TributeController {
  private tributes = [
    { id: 1, name: 'Aurum Galliae', amount: 50000 },
    { id: 2, name: 'Argentum Hispaniae', amount: 30000 },
  ];

  @Get(':id')
  findTribute(@Param('id', ParseIntPipe) id: number) {
    const tribute = this.tributes.find(t => t.id === id);
    if (!tribute) {
      // Throw 404 exception
      throw new NotFoundException(
        `Tributum ${id} non inventum! (Tribute not found)`
      );
    }
    return tribute;
  }

  @Post()
  @UseGuards(RolesGuard)
  createTribute(@Body() dto: any) {
    if (!dto.name || !dto.amount) {
      // Throw 400 exception
      throw new BadRequestException(
        'Tribute must contain a name and amount!'
      );
    }

    const exists = this.tributes.find(t => t.name === dto.name);
    if (exists) {
      // Throw 409 exception
      throw new ConflictException(
        `Tribute named "${dto.name}" already exists!`
      );
    }

    const newTribute = { id: this.tributes.length + 1, ...dto };
    this.tributes.push(newTribute);
    return newTribute;
  }
}

The throw keyword stops the method, and the NestJS exceptions layer sends the response for you. For a missing tribute the client gets this JSON:

{
  "message": "Tributum 3 non inventum! (Tribute not found)",
  "error": "Not Found",
  "statusCode": 404
}

Your text lands in the message field, while error and statusCode come from the exception class. When you need a code without a dedicated class, reach for the base HttpException with a value from the HttpStatus enum:

throw new HttpException('Error message', HttpStatus.I_AM_A_TEAPOT); // 418

Status 418 really exists, even though it was born as a joke. Beware of a plain throw new Error(): such an exception is not an HttpException, so the client only sees { "statusCode": 500, "message": "Internal server error" }. The error details stay on the server - and that is a good thing.

Creating custom Exception Filters

Your own verdict format comes from a class that implements the ExceptionFilter interface. The @Catch(HttpException) decorator says which cases go to this court, and the catch() method receives the exception and an ArgumentsHost - the object from which you take the request and the response:

// filters/roman-exception.filter.ts
import {
  ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class RomanExceptionFilter 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();

    // Custom error response format in empire style
    response.status(status).json({
      statusCode: status,
      imperium: 'Roma Aeterna',
      error: exception.message,
      path: request.url,
      method: request.method,
      timestamp: new Date().toISOString(),
    });
  }
}

First host.switchToHttp(), then the response and the request from that context, and finally sending the response. You can read the status from the exception (exception.getStatus()) anywhere before sending. This filter only changes the shape of the response - it copies the status code from the exception unchanged. One trap: for validation errors exception.message is the generic "Bad Request Exception", and the list of field errors sits in exception.getResponse().

Binding filters - tribunal levels

You attach a filter with the @UseFilters() decorator to a method or a controller, or globally for the whole application:

// 1. Method level - only this method
@Controller('tributa')
export class TributeController {
  @Get(':id')
  @UseFilters(new RomanExceptionFilter()) // Only for this method
  findTribute(@Param('id') id: string) {
    throw new NotFoundException('Tribute not found!');
  }
}

// 2. Controller level - entire controller
@Controller('legiones')
@UseFilters(RomanExceptionFilter) // Entire controller
export class LegionController {
  @Get(':id')
  findLegion(@Param('id') id: string) {
    throw new NotFoundException('Legion not found!');
  }
}

// 3. Global level - entire application (in main.ts)
// app.useGlobalFilters(new RomanExceptionFilter());

You can pass an instance (new RomanExceptionFilter()) or the class itself. The NestJS documentation recommends the class, because the framework can then reuse one instance across the whole module and inject its dependencies. app.useGlobalFilters() has two limitations: the filter is created outside the module system, so it gets no constructor dependencies, and it does not cover WebSocket gateways. That is why I prefer registering a global filter as a provider:

// app.module.ts - global filter registered as a provider
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { RomanExceptionFilter } from './filters/roman-exception.filter';

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

It works the same way as useGlobalFilters, but now the filter can inject, for example, a logger. That is my recommendation.

Catch-All Filter - the supreme tribunal

A filter with an empty @Catch() catches everything, including errors that are not an HttpException, such as a dropped database connection:

// filters/all-exceptions.filter.ts
import {
  ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus,
} from '@nestjs/common';

@Catch() // Without argument = catches EVERYTHING
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const status = exception instanceof HttpException
      ? exception.getStatus()
      : HttpStatus.INTERNAL_SERVER_ERROR;

    const message = exception instanceof HttpException
      ? exception.message
      : 'Internal empire server error!';

    response.status(status).json({
      statusCode: status,
      error: message,
      path: request.url,
      timestamp: new Date().toISOString(),
    });
  }
}

The instanceof operator splits two paths: HTTP exceptions keep their status and message, and everything else gets 500 and a generic text. Never send the client the exception.message of an unknown error - it could reveal database details. Write such an error to the logs instead. A single filter can also handle several types at once: @Catch(HttpException, TypeError).

Filter execution order

Filters are the only part of the request lifecycle that does not start at the global level:

  1. Method filter (if present) - checked first
  2. Controller filter (if present) - checked second
  3. Global filter (if present) - checked last

Only one filter handles an exception. If the method filter takes it, the controller filter and the global filter are not called. But when the method filter's @Catch() names a different exception type, the case goes up to the controller. At the same level, declare the catch-everything filter before the more specific one, so that the latter can still handle its own type.

In the next lesson you will see where in the request lifecycle filters do their work, and the whole of module 6 is devoted to error handling.

Remember: an exception is the accusation, and a filter is the tribunal that turns it into a clear verdict for the client.

Code for this lesson: src/exception-filters.ts
// Exception Filters - Courts and Tribunals of the Empire
import {
  ExceptionFilter, Catch, ArgumentsHost,
  HttpException, HttpStatus, NotFoundException,
  BadRequestException, ForbiddenException,
} from '@nestjs/common';

console.log("Exception Filters - the empire's court system!");

// ===========================================
// 1. Built-in NestJS exceptions
// ===========================================

function demonstrateExceptions() {
  // 404 Not Found
  // throw new NotFoundException('Tributum non inventum!');

  // 400 Bad Request
  // throw new BadRequestException('Missing required data!');

  // 403 Forbidden
  // throw new ForbiddenException('Access denied!');

  // Any HTTP code
  // throw new HttpException('Message', HttpStatus.I_AM_A_TEAPOT);

  console.log("Built-in exceptions: NotFoundException, BadRequestException...");
  console.log("Each generates the appropriate HTTP code automatically");
}

demonstrateExceptions();

// ===========================================
// 2. Custom Exception Filter
// ===========================================

@Catch(HttpException)
class RomanExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      imperium: 'Roma Aeterna',
      error: exception.message,
      path: request.url,
      timestamp: new Date().toISOString(),
    });
  }
}

console.log("\n@Catch(HttpException) - catches HTTP exceptions");
console.log("@Catch() - catches ALL exceptions");

// ===========================================
// 3. Binding filters
// ===========================================

console.log("\nBinding levels:");
console.log("@UseFilters(filter) on method - only that method");
console.log("@UseFilters(filter) on controller - entire controller");
console.log("app.useGlobalFilters(filter) - entire application");

console.log("\n=== EXCEPTION FILTERS SUMMARY ===");
console.log("HttpException - base HTTP exception");
console.log("@Catch(Type) - exception filter decorator");
console.log("ExceptionFilter - interface for implementation");
console.log("@UseFilters() - binding to method/controller");
console.log("Order: method > controller > global");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What HTTP code does throwing new NotFoundException() generate in NestJS?

  2. 2. What does the @Catch(HttpException) decorator on an exception filter class mean?

  3. 3. How do you create an exception filter that catches ALL exception types (not just HttpException)?

  4. 4. If a filter is defined at both the method and controller level, which one is executed first?

Hands-on tasks in the game

  • Code editor

    Write a RomanExceptionFilter with @Catch(HttpException) that returns JSON with fields: statusCode, imperium, error, path, timestamp

  • Vertical ordering

    Order the Exception Filter binding levels from the narrowest to the widest scope:

  • Click in order

    Arrange the parts of an exception filter's catch() method in the correct order:

  • Code editor

    Write an AllExceptionsFilter with @Catch() (no arguments) that handles both HttpException and other errors

  • Horizontal ordering

    Arrange the elements of throwing a 404 exception in NestJS:

  1. QuestionNotFoundException
  2. QuestionThe @Catch() Decorator
  3. Coding taskCustom Exception Filter
  4. Put in orderException Filter Binding Levels
  5. Click in orderStructure of the catch Method in a Filter
  6. QuestionCatch-All Exception Filter
  7. Coding taskCatch-All Exception Filter
  8. Put in orderThrowing a NotFoundException
  9. QuestionFilter Execution Order

Useful articles