import { assertThrows } from "jsr:@std/assert"
assertThrows(throw_error, "")
assertThrows(() => {
const my_fn = ((): string | undefined => (undefined))
const my_var = (my_fn() ?? throw_error("`my_var` was not supposed to be undefined"))!
typeof my_var satisfies string
}, "`my_var` was not supposed to be undefined")
assertThrows(
() => throw_error("liar liar", { pants: new Set(["on", "fire"]) }),
`liar liar { pants: Set(2) { "on", "fire" } }`
)
this function throws an error whenever called, and it logs the
messages
that you've provided it, in (almost) the same manner asconsole.log
would do.where is this function useful?
suppose you want to ensure that the value returned by a function
my_fn: <T>() => (T | undefined)
is non-nullable. and if it isundefined
, then the your current function scope to throw an error, so that it exits.typically, you would have to do something like:
but with this function, you can write more concise inline statements for invoking errors conditionally: