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

Strings instead of errors as an antipattern


One of the worst things you can do is to throw or return a string instead of an error. However, why is that? Let's describe a few features that the error objects have:

  • The stack property is fundamental, and it lets you know where the error originated from

  • Different types that allow us to treat errors distinctly (using instanceof for example)

  • Since an error is an object, we can assign custom properties on it

All of these functionalities are gone in an instant when you use strings instead of errors. However, let's take a look at a practical example:

// err-vs-string.js
var fs = require('fs');

function getWordCount(filename, callback) {
  fs.readFile(filename, 'utf-8', function(err, content) {
    if (err) { return callback(err); }

    return callback(null, content.split(' ').length);
  });
}

getWordCount('/i-dont-exist', function(err, length) {
  if (err) {
    if (err.code === 'ENOENT') {
      return console.error('File not found!');
    }

    throw...