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.
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...