Official NestJS documentation on exception filters, covering the built-in exceptions layer, HttpException class, custom exceptions, exception filters, and binding strategies.

Key takeaways

  • Nest has a built-in exceptions layer that catches all unhandled exceptions. Unrecognized exceptions (not HttpException or subclasses) produce a default { statusCode: 500, message: "Internal server error" } response.
  • HttpException(response, status, options?) is the base exception class. The response argument can be a string (overrides message) or object (overrides entire body). The optional options.cause provides error-cause chaining for logging.
  • Built-in HTTP exceptions: BadRequestException, NotFoundException, ForbiddenException, UnauthorizedException, InternalServerErrorException, etc. — all extend HttpException and are imported from @nestjs/common. They support cause and description options.
  • By default, built-in exceptions that extend IntrinsicException are not logged (treated as normal application flow).
  • Custom exception filters implement ExceptionFilter with catch(exception, host). Use @Catch(HttpException) to target specific exception types, or @Catch() to catch everything. Access Request/Response via host.switchToHttp().
  • ArgumentsHost is an abstraction that works across HTTP, Microservices, and WebSockets contexts, enabling generic exception filters.
  • Binding scopes: Method-scoped (@UseFilters(filter) on route), controller-scoped (@UseFilters(filter) on class), global-scoped (app.useGlobalFilters()). For DI support with global filters, use the APP_FILTER token in module providers.
  • Prefer passing classes (not instances) to @UseFilters() — this enables DI and reduces memory usage through instance reuse.
  • Catch-everything filters use @Catch() with HttpAdapterHost for platform-agnostic response delivery. Must be declared before type-specific filters.
  • Inheritance: Extend BaseExceptionFilter and call super.catch() to override default behavior. Global filters that extend BaseExceptionFilter need the HttpAdapter reference.

Entities and concepts

Connections to existing knowledge

Exception filters are the third major NestJS architectural feature after controllers and providers. The ArgumentsHost pattern is shared with guards and pipes but is first documented here. The scoping model (method → controller → global) is identical to the pipe scoping in NestJS Pipes, and both use the same APP_* token pattern for DI-enabled global registration. The execution model — where pipes, guards, and exception filters form layers around route handlers — means exceptions thrown in Pipes are handled by this same exceptions layer.