NestJS provides a comprehensive exception handling system through exception filters, platform-specific error handlers, and built-in HTTP exception types. The framework intercepts unhandled exceptions during request processing and transforms them into appropriate HTTP responses. Exception filters can be registered globally, at the module level, or for specific controllers and routes.
The exception handling system integrates with HTTP adapters (Express, Fastify) through setErrorHandler() and setNotFoundHandler() methods, providing platform-agnostic error handling while allowing platform-specific customizations.
For information about the broader request processing pipeline, see page 4. For guards, interceptors, and pipes that may throw exceptions, see page 4.4.
Exception filters are responsible for catching exceptions thrown during request processing and converting them into HTTP responses. NestJS processes exceptions through a layered system where filters are applied in a specific order: route-level filters, controller-level filters, and finally global filters.
Exception Filter Interface
Exception filters implement the ExceptionFilter interface with a catch() method that receives the exception and response objects.
Sources: packages/core/nest-application.ts396-408 packages/microservices/nest-microservice.ts167-185
Global exception filters are registered using the useGlobalFilters() method on the application instance. These filters apply to all routes across the entire application and serve as the final exception handler before the platform's error handler.
Global Filter Registration
Global filters are registered during application initialization and stored in the ApplicationConfig. The framework applies instance decorators if configured through the instrument.instanceDecorator option.
Microservices Support
The NestMicroservice class also supports global exception filters through the same useGlobalFilters() interface, allowing consistent error handling across HTTP and microservice transports.
Sources: packages/core/nest-application.ts396-408 packages/microservices/nest-microservice.ts167-185 packages/microservices/microservices-module.ts38-41
NestJS provides built-in HTTP exception classes that correspond to standard HTTP status codes. These exceptions extend a base exception class and automatically format error responses with appropriate status codes.
Built-in HTTP Exceptions
| Status Code | Exception Class | Common Use Case |
|---|---|---|
| 400 | BadRequestException | Invalid request parameters or validation failures |
| 401 | UnauthorizedException | Missing or invalid authentication credentials |
| 403 | ForbiddenException | Authenticated but lacking required permissions |
| 404 | NotFoundException | Requested resource does not exist |
| 409 | ConflictException | Request conflicts with current state |
| 422 | UnprocessableEntityException | Semantic validation failures |
| 500 | InternalServerErrorException | Unhandled server errors |
| 502 | BadGatewayException | Invalid response from upstream server |
| 503 | ServiceUnavailableException | Service temporarily unavailable |
Exception Response Format
HTTP exceptions generate responses with a statusCode property that triggers special handling in the platform adapters' reply() methods. When an error response contains statusCode >= HttpStatus.BAD_REQUEST, the adapters ensure the Content-Type is set to application/json.
Sources: packages/platform-fastify/adapters/fastify-adapter.ts471-481 packages/platform-express/adapters/express-adapter.ts138-149
HTTP adapters provide platform-specific error handling through setErrorHandler() and setNotFoundHandler() methods. These handlers integrate with the underlying HTTP framework (Express or Fastify) to process unhandled exceptions and 404 responses.
Express Error Handler
The ExpressAdapter registers error handlers as standard Express middleware using instance.use(). Express processes error middleware by signature (4 parameters) and executes them when exceptions occur.
Fastify Error Handler
The FastifyAdapter uses Fastify's native setErrorHandler() and setNotFoundHandler() methods, which provide type-safe error handling with proper request/reply context.
Error Handler Registration
The NestApplication registers error handlers during initialization through the registerRouterHooks() method, which calls registerNotFoundHandler() and registerExceptionHandler() on the routes resolver.
Sources: packages/platform-express/adapters/express-adapter.ts168-174 packages/platform-fastify/adapters/fastify-adapter.ts510-516 packages/core/nest-application.ts213-216
The platform adapters' reply() methods handle error response formatting, ensuring consistent JSON responses for exceptions. When the response body contains a statusCode property indicating an error (>= 400), the adapters automatically set the Content-Type to application/json.
Content-Type Enforcement
Both Express and Fastify adapters check if the response Content-Type matches the error body format. When a mismatch is detected (non-JSON Content-Type with an error status code), the adapters log a warning suggesting the use of a custom exception filter for non-JSON responses.
StreamableFile Support
The adapters also handle StreamableFile responses, automatically setting Content-Type, Content-Disposition, and Content-Length headers from the file metadata before streaming.
Sources: packages/platform-express/adapters/express-adapter.ts138-149 packages/platform-fastify/adapters/fastify-adapter.ts471-482
Custom exception filters allow applications to implement specialized error handling logic for specific exception types or scenarios. Exception filters can be bound at different scopes to provide granular control over error handling behavior.
Exception Filter Scopes
| Scope | Registration Method | Application Level |
|---|---|---|
| Global | app.useGlobalFilters() | Entire application |
| Controller | @UseFilters() decorator on controller | All routes in controller |
| Route | @UseFilters() decorator on method | Single route handler |
Filter Execution Order
Exception filters execute in order from most specific to most general:
@UseFilters() on handler)@UseFilters() on controller)useGlobalFilters())The first filter that handles the exception (doesn't rethrow) stops propagation.
Integration with GraphInspector
When global filters are registered, the framework tracks them using the GraphInspector by inserting orphaned enhancers with subtype 'filter'. This enables runtime inspection and debugging of the exception handling pipeline.
Sources: packages/core/nest-application.ts396-408 packages/microservices/nest-microservice.ts167-185
Exception handling behavior can be customized through various configuration options available across different pipe types.
Custom exception factories allow complete control over error handling:
Sources: packages/common/pipes/validation.pipe.ts26-36 packages/common/pipes/parse-int.pipe.ts17-34 packages/common/test/pipes/validation.pipe.spec.ts555-571