Last active
June 1, 2023 19:23
-
-
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[]`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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