Skip to content

Instantly share code, notes, and snippets.

@misaelabanto
Last active October 21, 2021 06:38
Show Gist options
  • Save misaelabanto/c345fbcc8117c214f368048cba005a15 to your computer and use it in GitHub Desktop.
Save misaelabanto/c345fbcc8117c214f368048cba005a15 to your computer and use it in GitHub Desktop.
Custom exception for nestjs validation errors. It uses default error message transform from nest.js. You can also configure this.
import { BadRequestException } from '@nestjs/common';
import { ValidationError } from 'class-validator';
import { iterate } from 'iterare';
const VALIDATION_ERROR = () => 'There are validation errors';
export class ValidationException extends BadRequestException {
code: string;
errors: string[];
constructor(errors: ValidationError[]) {
super(VALIDATION_ERROR());
this.code = VALIDATION_ERROR.name;
this.errors = this.flattenValidationErrors(errors);
}
private flattenValidationErrors(validationErrors: ValidationError[]) {
return iterate<ValidationError>(validationErrors)
.map((error) => this.mapChildrenToValidationErrors(error))
.flatten()
.filter((item) => !!item.constraints)
.map((item) => Object.values(item.constraints))
.flatten()
.toArray();
}
private mapChildrenToValidationErrors(
error: ValidationError,
parentPath?: string,
) {
if (!(error.children && error.children.length)) {
return [error];
}
const validationErrors: ValidationError[] = [];
parentPath = parentPath
? `${parentPath}.${error.property}`
: error.property;
for (const item of error.children) {
if (item.children && item.children.length) {
validationErrors.push(
...this.mapChildrenToValidationErrors(item, parentPath),
);
}
validationErrors.push(
this.prependConstraintsWithParentProp(parentPath, item),
);
}
return validationErrors;
}
private prependConstraintsWithParentProp(
parentPath: string,
error: ValidationError,
) {
const constraints = {};
for (const key in error.constraints) {
constraints[key] = `${parentPath}.${error.constraints[key]}`;
}
return Object.assign(Object.assign({}, error), { constraints });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment