When you are in a team where all of us handle one or more than one microservices talking to each other via HTTP protocol then error status code matters a lot.
There must be some sort of standard across all Microservices which everyone has to follow in order to have consistent and seamless integration with the user interface or mobile application.
In this short article, I am going to explain you the single tool you need to standardize the HTTP status code across all of the microservices.
Let’s begin.
Handling HTTP Status Code in Node
Generally, we set status code in Node.js like this.
const app = express();
const router = express.Router();
router.get('/', (req,res) => {
res.send('OK'); // Sends HTTP status code 200 back to browser
});
router.all('*',(req,res) => {
res.status(404).send('404 Invalid Request');
});
app.use('/',router);
app.listen(process.env.port || 3000);
The code above is simple Node.js code which sends responses back to the browser or API consumer.
We are handling status code 200 and 404 in it but there is various HTTP status code assigned for the various purpose.
For example, HTTP status code 401 is for Unauthorized access and 408 is for client timeout and so on.
To handle all of this status code, there is a smart package called Boom which can help you to standardize the HTTP status code in your Node.js project.
Installing Boom
You can install boom by running the following command inside your project directory.
Once it is installed, you can use it wherever you want to send back the HTTP response.
for example.
const app = express();
const Boom = require('boom')
const router = express.Router();
router.get('/', (req,res) => {
res.send('OK'); // Sends HTTP status code 200 back to browser
});
router.all('*',(req,res) => {
res.json(Boom.notFound('Invalid Request')); // this will set the status to 404
});
app.use('/',router);
app.listen(process.env.port || 3000);
You can find all of the HTTP status code and examples for each here.
I hope this quick read helps you in some way to handle those HTTP status codes like a pro!