this function throws an error whenever called, and it logs the messages that you've provided it, in (almost) the same manner as console.log would do.

Tip

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 is undefined, then the your current function scope to throw an error, so that it exits.

typically, you would have to do something like:

// example 1:
const my_var = my_fn()
if(my_var === undefined || my_var === null) {
throw Error("`my_var` was not supposed to be undefined")
}

// example 2:
const my_path = normalizePath("path/to/file.ts")
if(!my_path.startsWith("./")) {
throw Error(`expected a relative path, instead found: ${my_path}`)
}

but with this function, you can write more concise inline statements for invoking errors conditionally:

// example 1:
const my_var = (my_fn() ?? throw_error("`my_var` was not supposed to be undefined"))!

// example 2:
const
temp = normalizePath("path/to/file.ts"),
my_path = (temp.startsWith("./") ? temp : throw_error("expected a relative path, found:", temp))!
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" } }`
)