DEV Community

Cover image for ECOMMERCE Website Using MERN Part-4.1 ( Backend Error Handler {More Errors} )
Bikramjeet Sarmah
Bikramjeet Sarmah

Posted on • Updated on

ECOMMERCE Website Using MERN Part-4.1 ( Backend Error Handler {More Errors} )

In this blog we will be making the Error Handler for handling Unhandled Promise Rejection, Uncaught Exception, Cast Errors

Step-1 Unhandled Promise Rejection

This type of error occurs if there if any mistakes are there in our env variables
Env Variables

So to fix it we just add these codes

Here, we are using on() which takes two function, the error and a callback function. In the callback function we just log the error message and then close the server

The Server


Closing function of the server


Step-2 Now lets handle the uncaught exception error. This error occurs if there is an undefined variable.

This is the same as Step-1 just we change the first parameter to uncaughtException.

Step-3 Lets handle some MongoDb error.

Here the error comes if we gives an invalid ID in the routes
Mongo Error

We see a CastError so to fix this lets open error.js file and write these codes.
Mongo Error Code

The Code is pretty code simple, we just check the Error Code with an if-else statement & pass a new message with error code 400.

The error.js file will look like this

Error js

In future if there are more Errors we will just make it on the go.

In the next blog we will make paginations, search filters etc

Discussion (0)