404 error in a service is typically used to denote that the requested resource is not available. In this article we will see how to handle 404 error in express. Once express gets a request, it looks for matching middleware or routes. If it can’t find a match for the request, then it throws a 404 error. 404 errors are not captured by the typical error handlers as 404 is not an actual error instead its a resource not found scenario.

To handle a 404 error in express, we need to write a middleware function at the bottom stack. Take a look at the below example. We have a GET call along with a middleware function to handle the 404 errors.

var express = require("express");
var app = express();
//Express GET call
app.get('/calculate',function(req,res){
	res.send("Example GET");
});

//Capture All 404 errors
app.use(function (req,res,next){
	res.status(404).send('Unable to find the requested resource!');
});

app.listen(8080);

Run the above code and make a call to the server with a resource path that isn’t available. For example http://localhost:8080/hello. This will invoke the function to capture 404 error.

How to handle 404 error in express?