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
HttpExceptionor subclasses) produce a default{ statusCode: 500, message: "Internal server error" }response. HttpException(response, status, options?)is the base exception class. Theresponseargument can be a string (overrides message) or object (overrides entire body). The optionaloptions.causeprovides error-cause chaining for logging.- Built-in HTTP exceptions:
BadRequestException,NotFoundException,ForbiddenException,UnauthorizedException,InternalServerErrorException, etc. — all extendHttpExceptionand are imported from@nestjs/common. They supportcauseanddescriptionoptions. - By default, built-in exceptions that extend
IntrinsicExceptionare not logged (treated as normal application flow). - Custom exception filters implement
ExceptionFilterwithcatch(exception, host). Use@Catch(HttpException)to target specific exception types, or@Catch()to catch everything. AccessRequest/Responseviahost.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 theAPP_FILTERtoken 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()withHttpAdapterHostfor platform-agnostic response delivery. Must be declared before type-specific filters. - Inheritance: Extend
BaseExceptionFilterand callsuper.catch()to override default behavior. Global filters that extendBaseExceptionFilterneed theHttpAdapterreference.
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.