Saturday, September 3, 2022

NodeJS | Handling HTTP Error Status using Boom

 

Remembering status codes is a difficult task nowadays because there are so many HTTP status codes available that we encounter generally.

To handle all these status codes, there is a module called "Boom" which helps us to define the same standardized rule for our NodeJS application. So, we don't need to remember all these status codes.

What is Boom?

According to documentation:
Boom provides a set of utilities for returning HTTP Errors. It is an HTTP-friendly error object and part of the Hapi ecosystem which was designed to work seamlessly with the Hapi web framework and its other components.

Getting Started

Follow the step-by-step guide to learn about how we can apply Joi validation on our NodeJs and ExpressJS app:

Step 1:- Let's first create a directory named "nodejs_boom_error_handling" and initialize it using the npm command
  • mkdir nodejs_boom_error_handling
  • cd nodejs_boom_error_handling
  • npm init -y

Step 2:- Installing needed npm modules

After initializing the project, let's install all needed npm modules like express for the server, boom for error handling, and nodemon for self-starting the server if any changes occur by the following command:

npm install express @hapi/boom --save

npm install nodemon --save-dev

After installing these npm modules, your "package.json" file will look like this:

{
  "name": "nodejs_boom_error_handling",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",    "start": "nodemon index.js"  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@hapi/boom": "^10.0.0",
    "express": "^4.18.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.19"
  }
}


Step 3:- Setting up the server

After installing all needed npm modules. Let's first set up the server. For setting up the server, let's first create a server file name "index.js". You can create a file using the following command and by using the widgets.

touch index.js

After creating the server file. Let's create a server with an error handler. For creating the server you may copy the following code:

const express = require('express')
const app = express()
const PORT = process.env.PORT || 3000

// error handler
app.use(function (err, req, res, next) {
    return res.status(500).send({
        error: true,
        message: err
    });
});

app.listen(PORT, () => {
    console.log(`Server is running at ${PORT} port`)
})

Let's run the server by using the following command:

npm start

After starting the server your server may produce the following output:

[nodemon] 2.0.19
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Server is running at 3000 port


CONGRATULATIONS.....You've Successfully set up the server.

Step 4:- Creating APIs routes and controller

Before applying the Boom, we first create APIs for that. Let's create two folder name routes and a controller at the root location. Make a file in both folders' names "index.js". With the help of the following command:

mkdir Routes Controller
cd Routes
touch index.js
cd ../Controller
touch index.js


Let's first import the route's "index.js" file into our server file i.e., "index.js" just before the error handler.

...app.use('/', require('./Routes'))

After importing the routes file into our server. Let's create some routes and their corresponding controllers.


The following code is for the routes "index.js" file.

const router = require('express').Router()
const Controller = require('../Controller')

router.get('/', Controller.homePageController)

module.exports = router


The following code is for the controller "index.js" file.

const homePageController = async (req, res, next) => {
    try {
        res.status(200).send('Welcome to Home Page!!')
    } catch (error) {
        next(error)
    }
}

module.exports = {
    homePageController
}


Step 5:- Boom Set up

After setting up the server. Let's set up the Boom for sending any error.

For that scenario, I'm going to throw direct errors at the time when we hit any API request.

Let's create some routes inside the "index.js" file of the routes folder and their corresponding controller in the "index.js" of the controller folder and also import "@hapi/boom" inside the "index.js" file of the controller.

Following are the changes to the router's "index.js" file changes:

...router.get('/', Controller.homePageController)
router.all('/bad-data', Controller.badDataController)
router.all('/bad-gateway', Controller.gatewayController)
router.all('/bad-implementation', Controller.badImplementationController)

router.all('/*', Controller.notFoundController);...

Following are the changes to the controller's "index.js" file changes:

...
const badDataController = async (req, res, next) => {
    try {
        res.json(Boom.badData('Bad Data'));     // this will set the status to 422
    } catch (error) {
        next(error)
    }
}

const gatewayController = async (req, res, next) => {
    try {
        res.json(Boom.badGateway('Bad Gateway'));   // this will set the status to 502
    } catch (error) {
        next(error)
    }
}

const badImplementationController = async (req, res, next) => {
    try {
        res.json(Boom.badImplementation('Bad Implementation')); // this will set the status to 500
    } catch (error) {
        next(error)
    }
}

const notFoundController = async (req, res, next) => {
    try {
        res.json(Boom.notFound("Not Existed"));
    } catch (error) {
        next(error)
    }
}

module.exports = {
    homePageController,
    badDataController,
    gatewayController,
    badImplementationController,
    notFoundController
}


You can also visit my GitHub repository nodejs_boom_error_handling for that code in case you got any type of issues.


I recommend you to visit Boom documentation for more details.