User inputs are very unpredictable on the web. So error handling becomes very important while building any real-time web application.
Express facilitates very good support for error handling, with its connect middleware.
Page Not Found Error Handling In Express: Node.js
app.js
1 2 3 4 5 6 7 8 9 | app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); app.use(function(req, res){ res.send(404, "Not found :-("); }); app.get('/', function(req, res){ res.send("Homepage!"); }); |
When the user visits root of the website ( / ), a message called “Homepage!” is displayed to the user. But what if he tries to access a URL route which is not defined Ex: /user It displays Cannot GET /users message. We can set up a separate middleware to deal with situations like this. When we encounter a URL which doesn’t have a custom route definition, it’ll look for the file in the public directory, if the file is not found, it’ll look through our final middleware and executes whatever is present inside it.
User Not Found Error Handling In Express: Node.js
app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 | app.use(function(err, req, res, next){ res.send(404, err.message); next(); }); app.get('/user/:username', function(req, res, next){ if(req.params.username === 'kiran') { var err = new Error('User Not Found'); next(err); } res.send(req.params.username); }); |
In real world application, we need to validate the user request before trying to serve them data. Here, if the user requests /user/kiran we’ll let the user know that the user kiran is not present in our database. So we setup a custom error handling middleware for situations like this. Here we create an error object and set a message, and pass this error object as parameter to next. call to next passes the control to the middleware which matches its signature, and executes whatever is present inside the middleware. [ Note the presence of err object inside the middleware callback method. ]
Error Handling In Express: Node.js
[youtube https://www.youtube.com/watch?v=noBowQTXSS4]
Note: Error handling can significantly increase the performance of your web application, due to the fact that your application need not figure out what to do next, in case of an error. You explicitly write error handling code for most common situations and the application behaves in a predictable manner.
Call to next() passes the execution control to the next level.