Book Image

Mastering Web Application Development with Express

By : Alexandru Vladutu
Book Image

Mastering Web Application Development with Express

By: Alexandru Vladutu

Overview of this book

Table of Contents (18 chapters)
Mastering Web Application Development with Express
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Handling errors with middleware


Each time we call the next function inside a middleware or a route handler with an error parameter, it delegates that to the error-handling middleware. Express allows us to plug in a custom error handler, but by default, it just displays the error stack while developing and shows an Internal Server Error message in production.

In the development mode, the error page isn't greatly formatted by default, but we can load the errorHandler() middleware that used to be bundled with Express (https://www.npmjs.org/package/errorhandler) to sweeten the deal. Let's create a sample application with that handler and include a middleware that calls next with an error argument:

var express = require('express');   var app = express();
var errorHandler = require('errorhandler');

app.use(function(req, res, next) {
  next(new Error('custom thrown'));
});

app.use(errorHandler());

app.listen(7777);

Now, if we start that application and make any request to the server, the following...