@nestjs/common
>=10.0.0 <12.0.0postconditions13functions11last verified2026-06-24coverage score100%Postconditions: what we check
- ValidationPipe · validation-pipe-missing-peer-depserrorWhenValidationPipe is instantiated or used but class-validator or class-transformer packages are not installed. This is a common mistake — @nestjs/common lists these as peer dependencies (not direct dependencies), so they must be installed separately. When ValidationPipe.transform() is first called and tries to require class-validator or class-transformer, the loadPackage() utility logs an error and calls process.exit(1).Throws
process.exit(1) — the NestJS process terminates immediately. No exception is thrown to the caller. The error is logged: "The 'class-validator' package is missing. Please, make sure to install it to take advantage of ValidationPipe."Required handlingInstall peer dependencies: npm install class-validator class-transformer Or use validatorPackage/transformerPackage options to provide custom implementations: app.useGlobalPipes(new ValidationPipe({ validatorPackage: customValidatorPackage, transformerPackage: customTransformerPackage })); Note: This is a startup error — the app will crash on the first validated request if peer deps are missing. Cannot be caught with try-catch.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - ValidationPipe · validation-pipe-dto-validation-errorerrorWhenA request body, query param, or route param fails DTO validation — e.g., a required field is missing, a field has the wrong type, or a field fails a custom validator. class-validator returns an array of ValidationError objects, which are passed to the exceptionFactory. The default factory creates a BadRequestException with the flattened validation error messages.Throws
BadRequestException (extends HttpException, HTTP 400) with response body: { "statusCode": 400, "message": ["name must be a string", "email must be an email"], "error": "Bad Request" } When disableErrorMessages: true, the message array is replaced with a generic "Bad Request" string (hides details from clients). Custom exceptionFactory allows returning any HttpException subclass.Required handlingValidationPipe is typically registered globally and NestJS's default exception handler converts BadRequestException to a 400 HTTP response automatically. However, callers using ValidationPipe manually in code (not via decorator) must handle this: try { const validated = await validationPipe.transform(requestBody, metadata); // proceed with validated data } catch (error) { if (error instanceof BadRequestException) { // validation failed — return 400 to client return res.status(400).json(error.getResponse()); } throw error; } For global registration: app.useGlobalPipes(new ValidationPipe()) — NestJS handles the BadRequestException automatically. Use whitelist: true to strip unknown properties. Use forbidNonWhitelisted: true to throw on unknown properties. Use transform: true to auto-transform primitives (e.g., string "42" → number 42).costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisible - ParseIntPipe · parse-int-invalid-inputwarningWhenA route parameter or query string value is not a valid integer string. Common cases: - Decimal: "3.14" → fails (isNumeric requires /^-?\d+$/) - Empty string: "" → fails - Non-numeric: "abc", "id", "null", "undefined" → fails - Float: "3.0" → fails (decimal point present) - URL with string ID: GET /users/abc where :id is ParseIntPipe Note: "0", "-1", "42" all pass. Only integer-shaped numeric strings pass.Throws
BadRequestException (HTTP 400) with message: "Validation failed (numeric string is expected)" Response body: { "statusCode": 400, "message": "...", "error": "Bad Request" } Custom exceptionFactory or errorHttpStatusCode options can override this.Required handlingFor route handlers: NestJS's built-in exception handler converts BadRequestException to a 400 response automatically. No additional try-catch needed in normal usage. For custom usage or when the 400 should be handled differently: @Get(':id') async getUser(@Param('id', ParseIntPipe) id: number) { // id is guaranteed to be a number here // BadRequestException already thrown and handled by NestJS before this point } If you need to handle the error explicitly, use optional: true to return null/undefined instead of throwing, then handle the null case: new ParseIntPipe({ optional: true })costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisibleSources[1] - ParseBoolPipe · parse-bool-invalid-inputwarningWhenA route parameter or query string value is not a valid boolean string. ParseBoolPipe ONLY accepts: "true", "false", true (boolean), false (boolean). All of these FAIL: - "1", "0" — numeric booleans - "yes", "no" — natural language - "on", "off" — toggle strings - "TRUE", "FALSE" — case-sensitive! (these fail in v10-v11) - "" — empty string - undefined (without optional: true)Throws
BadRequestException (HTTP 400) with message: "Validation failed (boolean string is expected)" Custom exceptionFactory or errorHttpStatusCode options can override this.Required handlingUse ParseBoolPipe only for query params that will strictly be "true" or "false". For more flexible boolean parsing (accepting "1"/"0", "yes"/"no"), implement a custom pipe. Example with optional: @Query('active', new ParseBoolPipe({ optional: true })) active?: boolean For case-insensitive boolean parsing in older NestJS versions, transform first: @Query('active') active: string // get raw string // then: active?.toLowerCase() === 'true'costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisibleSources[1] - ParseUUIDPipe · parse-uuid-invalid-formatwarningWhenA route parameter or query string is not a valid UUID string. Common cases: - Numeric ID: "123", "42" — fails (not a UUID format) - Empty string: "" — fails - Non-string type: number passed directly — throws "value passed as UUID is not a string" - Wrong UUID version: v4 UUID passed when version: '3' is set - Malformed UUID: "not-a-uuid", partial UUID strings - SQL injection attempts: "1; DROP TABLE users" — fails UUID validationThrows
BadRequestException (HTTP 400) with message: "Validation failed (uuid is expected)" — when no version specified "Validation failed (uuid v 4 is expected)" — when version: '4' specified "The value passed as UUID is not a string" — when non-string value passedRequired handlingParseUUIDPipe is the standard way to validate UUID route parameters. NestJS handles the BadRequestException automatically for route handlers. Always use ParseUUIDPipe for any route that takes a UUID: @Get(':id') async getUser(@Param('id', ParseUUIDPipe) id: string) { // id is guaranteed to be a valid UUID here } Specify version for stricter validation (v4 is most common): @Param('id', new ParseUUIDPipe({ version: '4' })) id: string Note: ParseUUIDPipe validates FORMAT only — it does not check if the resource with that UUID exists. A NotFoundException should be thrown if the resource is not found after UUID validation passes.costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisibleSources[1] - ParseArrayPipe · parse-array-missing-or-invalidwarningWhenThe query parameter or value is missing (undefined/null/empty) and optional: true is not set. Or the value is a non-string, non-array type that cannot be parsed. The pipe throws "Validation failed (parsable array expected)". Note: if items type is specified and item validation fails, the inner ValidationPipe also throws BadRequestException for each invalid item.Throws
BadRequestException (HTTP 400) with message: "Validation failed (parsable array expected)" Or validation errors from inner ValidationPipe when items: SomeClass is specified and items fail class-validator rules.Required handlingUse optional: true when the array parameter is not required: @Query('tags', new ParseArrayPipe({ optional: true })) tags?: string[] For typed arrays with validation: @Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids: number[] Items with class validation (requires class-validator installed): @Query('filters', new ParseArrayPipe({ items: FilterDto })) filters: FilterDto[]costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisibleSources[1] - ParseFloatPipe · parse-float-invalid-inputwarningWhenA route parameter or query string is not a valid numeric string. Non-numeric strings fail: "abc", "price", "null", "", "NaN", "$3.14". Note: "3.14abc" PASSES (parseFloat ignores trailing non-numeric chars) — this can be surprising behavior. "Infinity" also passes (isFinite check only applies to the final parsed value behavior, not the string regex check in all versions).Throws
BadRequestException (HTTP 400) with message: "Validation failed (numeric string is expected)"Required handlingUse for @Query or @Param that accept decimal numbers: @Query('price', ParseFloatPipe) price: number Note the surprising "3.14abc" → 3.14 behavior: if you need strict numeric validation, add a custom validator or use class-validator's @IsNumber() on a DTO.costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisibleSources[1] - ParseEnumPipe · parse-enum-invalid-valuewarningWhenA route parameter or query string value is not one of the valid enum values. Case-sensitive: enum values must match exactly. For a Direction enum with values "ASC" and "DESC", the value "asc" (lowercase) fails. Numeric enums: passing the string "0" when the enum has value 0 may fail depending on how the enum is defined (string vs numeric enum type).Throws
BadRequestException (HTTP 400) with a message listing valid enum values. Example: "Validation failed (expected value to be one of the following values: ASC, DESC)"Required handlingUse ParseEnumPipe for query params that must match a specific set of values: enum Direction { ASC = 'ASC', DESC = 'DESC' } @Query('order', new ParseEnumPipe(Direction)) order: Direction For case-insensitive enum matching, use a custom pipe that uppercases before comparison. String enums (enum values are string literals) are most reliable. Avoid numeric enums with ParseEnumPipe — the string-to-number matching is inconsistent across NestJS versions.costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisibleSources[1] - ParseFilePipe · parse-file-missing-requiredwarningWhenA file upload handler expects a file (fileIsRequired is true by default) but no file was included in the request. This is the most common ParseFilePipe error — an endpoint that requires file upload receives a request without multipart/form-data or with an empty file field.Throws
BadRequestException (HTTP 400) with message: "File is required"Required handlingUse fileIsRequired: false when the file is optional: @UploadedFile( new ParseFilePipe({ fileIsRequired: false }) ) file?: Express.Multer.File For required files, rely on NestJS's default 400 response. Document in API spec that file is required so clients don't miss it.costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisibleSources[1] - ParseFilePipe · parse-file-validator-failederrorWhenOne of the validators passed to ParseFilePipe fails. Built-in validators: - MaxFileSizeValidator: file size exceeds maxSize (in bytes). Error: "Validation failed (expected size is less than X bytes, got Y bytes)" - FileTypeValidator: file MIME type doesn't match fileType regex. Error: "Validation failed (expected type is /pattern/)" Custom FileValidator implementations can return any error message.Throws
BadRequestException (HTTP 400) with the validator's error message. For MaxFileSizeValidator: "Validation failed (expected size is less than X bytes, got Y bytes)" For FileTypeValidator: "Validation failed (expected type is /image\/(jpeg|png)/)"Required handlingUse MaxFileSizeValidator to prevent oversized uploads (important for serverless and memory-limited environments): new ParseFilePipe({ validators: [ new MaxFileSizeValidator({ maxSize: 5 * 1024 * 1024 }), // 5MB new FileTypeValidator({ fileType: /image\/(jpeg|png|webp)/ }) ] }) Catch validation errors for custom error responses: try { const file = await parseFilePipe.transform(uploadedFile); } catch (error) { if (error instanceof BadRequestException) { return { error: 'File upload rejected', details: error.message }; } throw error; }costmediumin prodimmediate exceptionusers seedegraded performancevisibilityvisible - StandardSchemaValidationPipe · standard-schema-validation-pipe-validation-errorerrorWhenA value passed to StandardSchemaValidationPipe.transform() fails validation against the standard schema attached to the parameter metadata. Common cases: - A Zod / Valibot / ArkType schema reports issues for the input (missing required fields, wrong types, failed refinements) - A custom Standard Schema implementation's ~standard.validate() returns { issues: [...] } instead of { value: T } - The schema returns a Promise that resolves to issues (transform awaits) The pipe awaits validate() and throws synchronously after the await when result.issues is truthy.Throws
BadRequestException (HTTP 400) by default — the default exceptionFactory maps each issue's .message to a string and constructs new HttpErrorByCode[HttpStatus.BAD_REQUEST](messages). When errorHttpStatusCode is customized in the constructor options, the exception class changes (e.g. errorHttpStatusCode: 422 → UnprocessableEntityException). Custom exceptionFactory can return any HttpException subclass or other throwable.Required handlingWhen the pipe is registered globally or via @UsePipes(), NestJS's built-in exception handler converts BadRequestException to a 400 HTTP response automatically — no caller try-catch is needed in normal route-handler usage. For programmatic / manual usage (calling .transform() directly), wrap the call: const pipe = new StandardSchemaValidationPipe(); try { const validated = await pipe.transform(payload, metadata); // proceed with validated data } catch (error) { if (error instanceof BadRequestException) { return res.status(400).json(error.getResponse()); } throw error; } To customize the HTTP status code on validation failure: new StandardSchemaValidationPipe({ errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY, }); To customize the thrown exception entirely: new StandardSchemaValidationPipe({ exceptionFactory: (issues) => new MyDomainValidationError(issues), }); Note: this pipe is currently only accessible via deep import in 11.1.x: import { StandardSchemaValidationPipe } from '@nestjs/common/pipes/standard-schema-validation.pipe'; It is not re-exported from '@nestjs/common'.costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisible - Injectable · injectable-constructor-errorwarningWhenconstructor throws error during dependency injection (connection failure, initialization error)Throws
Error that prevents application startupRequired handlingInjectable class constructors SHOULD handle initialization errors gracefully or throw descriptive errors. Constructor errors during DI crash application startup with unclear error messages.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - Controller · controller-async-handler-errorerrorWhenasync route handler throws error or promise rejectsThrows
Error propagated to exception filter or default error handlerRequired handlingController route handlers MUST handle async errors with try-catch or let NestJS exception filters handle them. Unhandled async errors crash application if no exception filter is configured.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[5]
Sources
Every postcondition cites at least one of these. Grouped by source type; numbered to match the footnotes above.
- [1]docs.nestjs.com/pipesPipes
- [2]docs.nestjs.com/techniques/validationValidation
- [4]docs.nestjs.com/providersProviders
- [5]docs.nestjs.com/exception-filtersException Filters
- [3]github.com/standard-schema/standard-schemastandard-schema/standard-schema
Research notes
Curator notes from SOURCES.md captured when the profile was written so you can verify the reasoning, not just the rules.
Sources: @nestjs/common
Package: @nestjs/common
Version: 10.x, 11.x
Category: framework (NestJS core)
Status: ✅ Complete
Official Documentation
- Main Docs: https://docs.nestjs.com/
- Providers: https://docs.nestjs.com/providers
- Exception Filters: https://docs.nestjs.com/exception-filters
- Controllers: https://docs.nestjs.com/controllers
- npm: https://www.npmjs.com/package/@nestjs/common
Behavioral Requirements
DI Errors: Constructor failures during dependency injection Route Handler Errors: Unhandled async errors in controllers Injectable constructors should handle initialization errors Controller route handlers must handle async errors Use ExceptionFilter for centralized error handling
Contract Rationale
DI errors crash application startup: Constructor failures prevent boot Unhandled route errors crash application Exception filters provide consistent error handling
Created: 2026-02-26 Status: ✅ COMPLETE