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

A simple way to create custom errors


Sometimes, we need to create errors with additional properties so that we can treat them differently in our error handlers or simply to provide more information for logging and monitoring purposes.

Here are some practical examples extracted from our sample movie application (/routes/movies.js):

// First example.
if (!req.query.title) {
  var err = new Error('Missing search param');
  err.code = 422;
  return next(err);
}

// Second example.
if (!/^\d+$/.test(req.params.id)) {
  var err = new Error('Bad movie id');
  err.code = 422;
  return next(err);
}

Instead of directly calling next() using the error object, we need another two lines to create and extend it with the custom properties.

Fortunately, there are some modules that help us with this:

The custom-err module accepts two parameters: the first parameter is the error message...