ExpressJS use middleware pattern for the router handling. Express provides simple middleware which can be used to handle any run-time errors. In any case, if run-time errors happen in your app.js then, the app.js will not stop, rather it will call the error handling middleware. When we use express middleware we pass three parameters (req, res, next). If we use error handler middleware then we will pass one extra parameter, which is the error (error, req, res, next).

Sample Code:

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();
});
app.listen(3000);

Here is same app.js code but with Error handling middleware:

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();
});

Error handling middleware:

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

Now, We are going to use the concept. First, create a new directory, then generate package.json in it. The recommended way is to use npm init command.

Install Express module

Run the following command in terminal to install express in your project.

npm install --save express

Example :

Here is simple Express Server with error handler middleware. Create a file name Server.js. Write the following code in Server.js :

var express = require('express');
var app = express();
var router = express.Router();
router.get('/', function (req, res) {
    res.send("Hello User");
});
app.use('/', router);
app.use(function (err, req, res, next) {
    console.log(err.stack);
    res.status(500).send({
        "Error": err.stack
    });
});
app.listen(3001);

Run Command :

C:\Users\Your Name>node server.js

Visit localhost:3001 to view the result.

To generate the run-time error, we will throw a random error and see whether it catches it or not. Run the app and hit localhost:3000 URL. We will get some error in console and in Web browser too.

Learn More: