In this blog post we will learn how to format NestJS validation error messages into key-value pairs for improved usability in client applications.
Introduction
When working with validation in nestjs with class-validators and class-transformers,
the error messages thrown in a single array which isn't much helpful for the client applications.
In this blog post, we will look into formatting the error messages from this
to this
The Setup
Let's create a new nestjs project and install necessary dependencies
With these commands, we have created a new nestjs project, and created a users module with dummy CRUD operations. Your app.modules.ts should look something like this
Let's now install packages to start validating the requests
To start using the validation pipe, let's modify main.ts
Now let's create a CreateUserDto that we will use to validate post request to the route /users
We've now added validations for each field. We will now use this dto in the post route
At this point if you make a post request to the route /users you will get errors in the following format.
We are validating the request but we can't really associate the error messages to it's respective field. It would be really helpful if we get the error messages with it's respective key.
To achieve that, let's create an exception filter that we can use in our validation pipe. For now to see the structure of the errors we will just log the errors
If you see the console, you will see the structure of the validation errors.
Now we know that the property will have the key of the field and the error messages will come in the constraints so let's use this knowledge and update our exception factory to structure our error messages
Now if you send a post request to the /users route, the error messages will be structured in key value pair
This is super helpful. Now the client applications can display error messages with their respective fields. But we're not done yet. Our exception factory works for simple fields like but when we pass nested values it will not be able to handle the it.
For the sake of the demo, let's say we wan't to create multiple posts along with the user in a single request.
Now try sending a post request to /users
You will most likely get a 500 error. When you log the validation errors, error with property posts will have children which will be array of ValidationError. Let's re-write our exception factory to handle this.
Here we're going through each error and recursively formatting error messages if there's a nested field. Now if you send a post request again, you should see well structured error messages.