feat(common): add new flatten options to validation pipe #14359
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
What is the current behavior?
Currently, when the validation pipe throws an error, the error messages are always flattened into an array of strings. For example:
This behavior lacks flexibility for scenarios where the original structured error format is needed.
Also for custom
exceptionFactory
the errors are always returned as an array of ValidationError. For example:What is the new behavior?
This PR introduces a new two options
disableFlattenErrorMessages
andflatExceptionFactoryMessage
in the ValidationPipe to control the formatting of error messages.disableFlattenErrorMessages
When this option is enabled, the errors will retain their original structure instead of being flattened.
For example:
The errors will now be returned in the
ValidationError
structured format:flatExceptionFactoryMessage
When this option is enabled, and
exceptionFactory
is provided, the errors passed to exception factory will be flattened as array of stringsFor example:
The errors will now be in format:
Does this PR introduce a breaking change?
Other information
Motivation
The motivation behind this change stems from a specific use case with WebSocket validation. When using the validation pipe with WebSockets (WebSocket Pipes Documentation), the error messages were not flattened by default. However, when I needed to flatten them, I ended up duplicating the same flattening logic in my exception handler. so I made it configurable.
Docs PR: nestjs/docs.nestjs.com#3173