Skip to content

Instantly share code, notes, and snippets.

@Nifled
Last active June 1, 2023 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nifled/5404a4c76b87f7597865b1da2594ba2d to your computer and use it in GitHub Desktop.
Save Nifled/5404a4c76b87f7597865b1da2594ba2d to your computer and use it in GitHub Desktop.
Format array of `ValidationError` similar to `class-validator`'s default format. This is handy when creating calling `validate` (which returns `ValidationError[]`
import { validate } from 'class-validator';
const validationErrors = await validate(objInstance);
if (validationErrors.length > 0) {
throw new BadRequestException(
validationErrors.map(
({ property, constraints }) =>
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
`${property}: ${Object.values(constraints!)[0]}`,
),
);
}
/**
This will effectively spit out output the following format:
{
"statusCode": 400,
"message": [
"limit: limit must not be less than 1",
"offset: offset must not be less than 0"
],
"error": "Bad Request"
}
In this case I used it to throw a BadRequestException, but the same can be done with any type of error
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment