When writing a function in JavaScript that has a conditional with a failure condition, one can utilize the Error
object which has the advantage of collecting a stack trace whenever a failure condition is met.
The message
property of this global object allows for creation of a custom error message in a simple manner:
let t = true, f = false
function assert(condition, message) {
if (!condition) {
throw new Error(message || "Assertion failed")
}
}
assert(f)
In VSCode (with Quokka):
Assertion failedβ
βββββat ββββββββassertβββ βquokka.js:5:9β
βββββat ββββββquokka.js:9:1
In PlayCode:
Error: Assertion failed
[email protected]://preview-empty_javascript.playcode.io/ line 18 > injectedScript:46:11
@https://preview-empty_javascript.playcode.io/ line 18 > injectedScript:50:7
[email protected]://preview-empty_javascript.playcode.io/ line 6 > injectedScript:18:5449
Getting a stack trace for custom logic is really useful when doing testing and debugging.
#TIL
#TheMoreYouKnow