Skip to content

Instantly share code, notes, and snippets.

@ianb
Last active Dec 16, 2015
Embed
What would you like to do?
assert() for Javascript
function AssertionError(msg) {
this.message = msg || "";
this.name = "AssertionError";
}
AssertionError.prototype = Error.prototype;
/* Call assert(cond, description1, ...)
An AssertionError will be thrown if the cond is false. All parameters will be logged to the console,
and be part of the error.
*/
function assert(cond) {
if (! cond) {
var args = ["Assertion error:"].concat(Array.prototype.slice.call(arguments, 1));
console.error.apply(console, args);
// This is mostly for Firefox, and should perhaps be conditional on that;
// this is because the standard Web Console often doesn't show proper stacks for errors
// (depending on where the error was thrown)
if (console.trace) {
console.trace();
}
throw new AssertionError(args.join(" "));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment