There is a handy shortcut in the node.js global console
to check if an expression is true and throw an exception if it's not. The shortcut is console.assert
and will perform the same action as executing require('assert').ok
. This is particularly useful for validating incoming parameters to a function. Below is an example that checks if required parameter is provided and throw an exception if it's missing.
function getUser (id) {
console.assert(id, 'ID is required');
...
}
Traditionally, you would either have a helper assert function or would manually need to check that the ID is valid and then throw an Error.
Even faster still is creating a shortcut to console.assert
to prevent the extra lookup. I would place this near the module requires and call it assert. This should be safe as long as you do not depend on the assert module for anything outside of the default ok
function. Below is an example:
var assert = console.assert;
function getUser (id) {
assert(id, 'id is required');
...
}
In researching this post I noticed that the assert.ok
function actually checks !!!(expression)
while console.assert
is doing !(expression)
. Interestingly, they will both have the same result. This would be untrue if you were checking (expression)
vs. !!(expression)
. But, ! will convert the expression to a boolean, so you don't have to worry about truthiness.