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 core of this system is the HttpException class and its specialized subclasses, which are processed by the ExceptionsHandler to produce consistent JSON responses.
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 Invocation
The ExceptionsHandler manages the execution of custom filters. It uses invokeCustomFilters() to iterate through registered filters and uses selectExceptionFilterMetadata() to find a match based on the exception type packages/core/exceptions/exceptions-handler.ts26-37 If no custom filter matches, it delegates to the BaseExceptionFilter packages/core/exceptions/exceptions-handler.ts16
Sources: packages/core/exceptions/exceptions-handler.ts9-38 packages/common/utils/select-exception-filter-metadata.util.ts1-15
The HttpException class is the foundation for all HTTP-related errors in NestJS. It extends IntrinsicException and provides utilities for response body creation and error chaining packages/common/exceptions/http.exception.ts27
By default, an HttpException response body contains:
statusCode: The HTTP status code packages/common/exceptions/http.exception.ts53message: A short description of the error packages/common/exceptions/http.exception.ts54cause property via HttpExceptionOptions packages/common/exceptions/http.exception.ts8-12 packages/common/exceptions/http.exception.ts84-89createBody() method handles different input types (string, object, or array) to ensure a standard HttpExceptionBody structure packages/common/exceptions/http.exception.ts115-149[object Object] by checking if the response is an object or string packages/common/test/exceptions/http.exception.spec.ts151-174Sources: packages/common/exceptions/http.exception.ts27-186 packages/common/test/exceptions/http.exception.spec.ts28-61
NestJS provides a wide array of built-in exceptions that inherit from HttpException. Each automatically sets the correct HttpStatus code.
| Exception Class | Status Code | Default Message |
|---|---|---|
BadRequestException | 400 | "Bad Request" |
UnauthorizedException | 401 | "Unauthorized" |
ForbiddenException | 403 | "Forbidden" |
NotFoundException | 404 | "Not Found" |
NotAcceptableException | 406 | "Not Acceptable" |
ConflictException | 409 | "Conflict" |
GoneException | 410 | "Gone" |
ImATeapotException | 418 | "I'm a teapot" |
InternalServerErrorException | 500 | "Internal Server Error" |
BadGatewayException | 502 | "Bad Gateway" |
Customizing Built-in Exceptions
Built-in exceptions accept a custom message/object and an optional description. For example, BadRequestException uses HttpException.extractDescriptionAndOptionsFrom() to parse arguments packages/common/exceptions/bad-request.exception.ts40-41
Sources: packages/common/test/exceptions/http.exception.spec.ts63-130 packages/common/exceptions/bad-request.exception.ts11-53 packages/common/exceptions/im-a-teapot.exception.ts14-56
Beyond HTTP errors, NestJS uses a specific hierarchy for framework-level errors during the bootstrap or injection process. These often extend RuntimeException.
The UnknownDependenciesException is thrown when the DI container cannot resolve a provider packages/core/errors/exceptions/unknown-dependencies.exception.ts6-18 It generates highly detailed error messages using UNKNOWN_DEPENDENCIES_MESSAGE to help developers debug their modules packages/core/errors/messages.ts63-141
Sources: packages/core/errors/exceptions/unknown-dependencies.exception.ts9-17 packages/core/errors/messages.ts63-141 packages/core/test/errors/test/messages.spec.ts16-89
NestJS abstracts exception handling across different protocols, using specialized handlers for each.
WsExceptionsHandler to process errors within gateway contexts.RpcExceptionsHandler for transport-specific error propagation.ExpressAdapter handles response formatting, ensuring that if a statusCode >= 400 is present in the body, the Content-Type is set to application/json packages/platform-express/adapters/express-adapter.ts138-149FastifyAdapter enforces JSON headers for error statuses packages/platform-fastify/adapters/fastify-adapter.ts471-482Sources: packages/core/exceptions/exceptions-handler.ts9-17 packages/platform-express/adapters/express-adapter.ts138-149 packages/platform-fastify/adapters/fastify-adapter.ts471-482
The framework includes a centralized message generator in packages/core/errors/messages.ts to ensure consistency in developer-facing error logs.
getDependencyName function determines if a dependency should be displayed as a class name, a symbol, or a string token packages/core/errors/messages.ts34-50getModuleName identifies the module context where the error occurred packages/core/errors/messages.ts57-58UNDEFINED_FORWARDREF_MESSAGE specifically targets common issues with circular references between modules packages/core/errors/messages.ts148-154Sources: packages/core/errors/messages.ts13-61 packages/core/test/errors/test/messages.spec.ts136-171