Last active
December 16, 2015 17:19
-
-
Save ianb/5470043 to your computer and use it in GitHub Desktop.
assert() for Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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