Skip to content

Instantly share code, notes, and snippets.

@ianb
Last active December 16, 2015 17:19
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ianb/5470043 to your computer and use it in GitHub Desktop.
Save ianb/5470043 to your computer and use it in GitHub Desktop.
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