The Node Error Handling Middleware

Raphael Sani Enejo (SanRaph)
5 min readMar 17, 2022

Handling errors in Node can be very tricky, for one you may resort to forwarding errors to Next in all your routes or stick to creating new instances of the Error class but could error handling ever be better? Let’s find out.

The true question is where do those errors end? as in, their final destination.
If you are building a pipeline of middlewares in your node application make sure you have an error-handling middleware as well because Node is not so good at giving default errors.

The default Cannot GET / error that Node gives.

This is the default error Node gives you when you request a route that does not exist. This is what we are going to take a look at in this article and see how properly we can handle it.

What that error is saying is that it can not find the route you are asking for, the slash route is always an entry point to a node js app which does not exist at the moment because we haven’t created it yet. This error is NOT very useful because it’s not clear and many people just take it but let’s know what truly is happening within the server.

That moment you request a slash (/) route, Node tells you it does not exists, this is Node's way of handling NotFound error.

What happens when you provide the route?

Having written the route, when you request it, you now get what you specified in the response, in our case, an object with the message: ‘OK’ and status:200.

The / route that Node couldn’t find.

Our Not Found Error Handler

Instead of the default Not Found error, let's write our own by creating an instance of Error class with the message Not the route you want as shown below.

This not-found middleware should be the last middleware so as to register every other route that may throw errors in your code.

The notFound middleware is specifically for NOT FOUND routes.

We create a new error because if we reach here, this middleware then definitely Node can not find what it is looking for, which is the route they input in the browser of which we retrieved and attached to the error message using req.originalUrl, therefore, bringing us to this point and if this error is anything other than not found error, it will then throw it to the Error-handling middleware itself using Next() like shown below.

Error Handling Middleware

Error Handling Middleware.

First off, is that the unique and most important thing about error handling middleware is this, it has four parameters instead of three which includes an error, req, res, and next parameters.

If you misspell any of the parameters, it will take it to be req, res, and next with the wrong name. req, res, and next are the normal parameters of a function handling a route however the error middleware has four. With this emphasis, I am not expecting you to forget.

In the code above, we get the status code of the incoming request. After creating it as statusCode variable, we checked to see if the code is 200, if it is 200 we then know that there is nothing wrong with the request, it must be a server error (designated a 500 status code), otherwise, give us the accompanied status code because it may neither be 200 nor 500. In the case where the status code is 404 in our NotFound middleware when that code is forwarded to the Error Handling Middleware, it will handle it as 404, not 200 nor 500.

In the file below you can see 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 them as middlewares in the index file in this manner.

The file is brought in on line seven, in lines seventeen and eighteen, you see, they are used as middleware, middlewares have a waterfall arrangement to allow incoming requests to pass through as a means of effecting all the usage of middlewares in the same way water run through pipes and get sieved before usage.

Every time you see use(), that’s a middleware and in the code, we placed them below our routes in order to register every route, any error that cannot be dealt with by any of the routes will be forwarded to the middleware, the first middleware searches to see if it’s a not-found error, if not, sends it to the error-handling middleware which gives us this in development.

Error message and stack.

Conclusion

There are many ways people handle errors in Node using the Error class, the recommended way is using the error middleware designed into Node.

Caution!

One thing you should be very careful doing is displaying your error stack in production, we are doing it here because we are on our development server, make sure you set your process.env.NODE_ENV to development because if you do this in production, you are giving away your file structure and myriad information to a hacker who could target your application, and you wouldn’t want this so handle it quickly and that’s it, your errors now reflect who you are, haha! the Grand One.

You have a busy day to run so, let’s wrap it up here so that you can go back to writing good code that changes lives. If anything seems a blur, don’t be skeptical, hit me in the comments and we can discuss it, or better yet, figure it out together.

--

--

Raphael Sani Enejo (SanRaph)

A Software Engineer with a strong user focus. Extensive experience in developing robust code and building world-class applications and life-changing products.