The validator in Express.js and error handling

Eddy Gao
3 min readFeb 25, 2021

--

Before we start our journey, this is my API file structure:

Files Structure and its function

Models

models folder contains the schema of each model to use with mongoose, check on my previous blog to learn the data schema if you’re not familiar with the MongoDB data schema with Node.js.

Routes

routes folder is where you handle the HTTP request from your browser such as the form submitted by the user.

Install npm package ‘express-validator’ , then Import { body } from express-validator to validate the data.

{ body } is a function where you specifies which data you want to validates and how to validates it. Check on express-validator document to learn more available validations.

Controllers

controllers folder is where you control your model before save it into your database.

Error Handling

Creation Error

To handle a creation error we’re using express-validator

if the validation fails, it’s going to throw an error with the message “Validation failed.” and change the status code of the server to 422, to inform the front-end the error is happening on the server-side with a status code of 422. Check more status codes from MDN.

With .catch if any internal server-side error happens and there is no error status code found, we set it to 500 since there is an error happening but just not specific.

Update/Read/Delete

to update or read or delete data usually need to specify which data the user wants to read. So it might require ObjectId to read on the data. Therefore, the error handling will be most often on finding the object.

When the user is not found, we throw and error with status code of 404.

Authorization

For the project, I also implemented jwt to authorize the user. I created an is-auth file in the middleware folder. And I use them for all the routes that require an authorized user.

If it’s not authorized or if the token is wrong, throw an error with not authenticate and status of 401.

--

--

No responses yet