Error handling in Express using Middleware

Express adopts middleware design pattern for the router handling. Express also provides us simple middleware which we can use to handle any run-time errors i.e in case of run-time errors your app will not stop, rather it will call the error handling middle-ware.

Related learning : How to write custom middle-ware in Express

A quick picture

In general when we use Express middle-ware we pass three fields :

(req,res,next)

In case of error handler middle-ware we pass one extra parameter, which is error one.

(error,req,res,next)

Sample code to get started

Consider following Express.js code with middle-wares.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser);

app.use(function(req,res,next) {
  console.log("In second route");
  next(); // go to next route.
});

app.listen(3000);

Here is same Express.js code but with Error handling middle-ware.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser);

app.use(function(req,res,next) {
  console.log("In second route");
  next(); // go to next route.
});

// Error handling middle-ware

app.use(function(err,req,res,next) {
  console.log("Error happens",err.stack);
});

app.listen(3000);

Sample project

Let’s develop small project to prove this concept. Create new directory and generate package.json in it. Recommended way is to use npm init command.

Error handling express

Here is my package.json.

package.json
{
  "name": "express-handler",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "Shahid Shaikh",
  "license": "MIT"
}

Let’s install Express module. Run following command in terminal to install it in your project.

npm i --save express

You may need to provide sudo access to it. Let’s code our Server.

Express Server

Here is simple Express Server with error handler middle-ware.

Server.js
var express = require('express');
var app = express();
var router = express.Router();

router.get('/',function(req,res) {
  res.send("Hello World!");
});

app.use('/',router);

app.use(function(err,req,res,next) {
  console.log(err.stack);
  res.status(500).send({"Error" : err.stack});
});

app.listen(3000);

Run the app using node Server.js command and visit localhost:3000 to view the app. However we need to validate whether our error handler logic is working or not. To generate the run-time error, we will throw random error and see whether it catches it or not.

Server.js
var express = require('express');
var app = express();
var router = express.Router();

router.get('/',function(req,res) {
  throw new Error();
  res.send("Hello World!");
});

app.use('/',router);

app.use(function(err,req,res,next) {
  console.log(err.stack);
  res.status(500).send({"Error" : err.stack});
});

app.listen(3000);

Run the app and hit localhost:3000 url. You should see following error in console and in browser too.

Error handling Express

Error handling in Express
I did press CTRL+C

This works!

Conclusion

Express is no doubt first choice of Node.js developer for developing the web application. Express error handling middle-ware is very helpful in catching globally occurring errors without worrying about the Server to crash.

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

2 Comments

  1. Nice Post!!.. Any ideas on how to extend this to handle 404 page redirecting or json errors? Thanks a lot

    1. 404 is very easy.

      All you need is to add this route at the end.

      // put at the end of every route and before the error handler.
      app.use("*",function(req,res) {
        res.send() or res.json()
      });

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.