Apps Development, Cloud Computing

4 Mins Read

Error-Handling Middleware in Node.js for Building Robust And Reliable Applications

Introduction

Dealing with errors in NodeJS can pose a challenge. You might either pass on errors to next in all your routes or generate fresh instances of the Error class. Nevertheless, can we improve error handling further? That’s what we need to explore.

The crucial issue is: where do these errors ultimately terminate? If you’re developing a sequence of middleware for your NodeJS application, including error-handling middleware is vital. This is because Node doesn’t offer reliable default errors.

In this article, we will examine Node’s default error message when attempting to access a non-existent route. We will investigate how to handle it effectively. Initially, the browser will provide you with – ‘Cannot GET /’

Route Working

When you request a route that does not exist, Node generates an error indicating that it cannot find the route you seek. The slash route is an entry point to a Node JS app, which does not exist yet since we haven’t created it. Unfortunately, this error is not very informative, and many individuals accept it. However, let’s explore what is happening within the server.

If you request the slash (/) route, Node informs you that it does not exist, which is how to handle the NotFound error. What happens when you provide the route? Once you’ve defined the route, requesting it will result in the response you specified, which in our case is an object with the message “Route Working” and a status of success, which is a status code of 200.

Pioneers in Cloud Consulting & Migration Services

  • Reduced infrastructural costs
  • Accelerated application deployment
Get Started

Not Found Error Handler

Rather than utilizing the default Not Found error, we can generate our own by constructing an instance of the Error class with the message “Route not present” as demonstrated below.

To ensure that all other routes that might generate errors in your code are registered, placing this notFound middleware at the end is essential.

Error Handling Middleware

The primary and most significant aspect of the error handling middleware is that it has four parameters instead of the typical three. These parameters include an error, req, res, and next.

It’s critical to note that misspelling any of the parameters will result in the function assuming that it only has the standard req, res, and next parameters with incorrect names. While req, res, and next are typical parameters for a function handling a route, the error middleware has four.

In the above code, we obtain the incoming request’s status code. After saving it as the statusCode variable, we check if the code is 200. If it is 200, we know there is nothing wrong with the request; it must be a server error, indicated by a 500 status code. Otherwise, provide the associated status code, which may be neither 200 nor 500. In our notFound middleware, if the status code is 404, when that code is passed on to the Error Handling Middleware, it will handle it as 404, not 200 or 500.

In the following file, you can view the two functions exported as an object to be used in the index file.

We exported this file and imported it in again as an object to use as middleware in the index file in this manner.

The file is imported on line second, and on lines thirteen and fourteen, they are utilized as middleware. Middlewares have a waterfall arrangement that permits incoming requests to pass through, similar to how water runs through pipes and gets filtered before use.

Each use() function is a middleware, and in the code, we positioned them beneath our routes to register every route. Any error that any of the routes cannot handle is forwarded to the middleware. The first middleware looks to see if it’s a non-found error. If it isn’t, it passes it on to the error-handling middleware, which gives us this output during development.

Our output for the available route, i.e., localhost:3001, will be –

error

But for non-available URLs like localhost:3000/api will be –

error2

Conclusion

Implementing error-handling middleware in Node.js is crucial for building robust and reliable applications. By properly handling errors, we can improve the user experience, provide meaningful feedback, and ensure the application remains stable despite unexpected errors.

This blog explored various techniques and best practices for handling errors in Node.js. We learned about the importance of structured error objects, handling synchronous and asynchronous errors, and different strategies for centralizing error handling.

By implementing error-handling middleware, we can capture and process errors consistently across our application. This allows us to customize error responses, log error details for debugging purposes, and gracefully handle exceptions to prevent application crashes.

Making IT Networks Enterprise-ready – Cloud Management Services

  • Accelerated cloud migration
  • End-to-end view of the cloud environment
Get Started

About CloudThat

CloudThat is an official AWS (Amazon Web Services) Advanced Consulting Partner and Training partner and Microsoft Gold Partner, helping people develop knowledge of the cloud and help their businesses aim for higher goals using best-in-industry cloud computing practices and expertise. We are on a mission to build a robust cloud computing ecosystem by disseminating knowledge on technological intricacies within the cloud space. Our blogs, webinars, case studies, and white papers enable all the stakeholders in the cloud computing sphere.

Drop a query if you have any questions regarding Error-Handling Middleware, NodeJS, I will get back to you quickly.

To get started, go through our Consultancy page and Managed Services Package, CloudThat’s offerings.

FAQs

1. Can we display the error stack in production?

ANS: – No, we should be very careful displaying your error stack in production because if you do this in production, you are giving away your file structure information to a hacker who could target your application.

2. Can we use it to handle other errors?

ANS: – Yes, you can enhance this middleware for different errors.

WRITTEN BY Satyam Dhote

Share

Comments

    Click to Comment

Get The Most Out Of Us

Our support doesn't end here. We have monthly newsletters, study guides, practice questions, and more to assist you in upgrading your cloud career. Subscribe to get them all!