In this express article we will see how to handle error in express. The idea is that we once should be able to handle errors and exceptions gracefully. In order to handle errors, express uses the middle ware function app.use() along with a call back function. The call back function takes four arguments; the error, request, response and next like below.

app.use(function(err, req, res, next){
});

Now, let us take a look at an example.

Express Error Handing Example

In this example, first we create an express GET service and introduce an error in it. Then we will use the error handling function to capture the error and send a response. Here we are introducing the error in the GET method by using an undefined variable “y”.

var express = require("express");
var app = express();
//Express GET call
app.get('/calculate',function(req,res){
	//Introduce error by using undefined variable 'y'
	var x = y + 10;
	res.send(x.toString());
});

//Capture All Errors
app.use(function (err,req,res,next){
	//Set status code to 500 and send a custom text
	res.status(500).send('Something is not quite right!');
});

app.listen(8080);

Run the above code and make a call to http://localhost:8080/calculate, you will see the error function gets executed.

Error Handling In Express