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

Ways of delivering errors in the Node applications


Due to the asynchronous nature of Node, there are two additional ways to deliver errors while writing applications, besides the synchronous style: using callbacks that have the error as the first parameter and for the more complicated cases (streams, for example), emitting error events.

Throwing errors in the synchronous style

A common situation to throw errors synchronously is when we call a function with the wrong parameters, as shown in the following example:

function startServer(port) {
  if (typeof port !== 'number') {
    throw new Error('port should be a number');
  }

  // Do stuff.
}

startServer('8888');

The preceding program will throw an error (which can be caught using try and catch) because the parameter has a wrong type. There is a more elegant way to achieve the same result using the native assert module:

var assert = require('assert');

function startServer(port) {
  assert.equal(typeof (port), 'number', 'port should be a number...