Assertions

assert.throws()

Verifies that a synchronous function throws and optionally matches the thrown error. Pass a function, not the result of calling it. Use rejects for promise failures. Tested on Node.js 22.16.0. Example output (one line per entry): ["matched", "ERR_ASSERTION"].

Formal Syntax & Structure

nodejs syntaxnodejs
assert.throws(fn[, error][, message])

Parameters & Attributes

NameTypeDescription
fnFunctionOperation expected to throw.
errorRegExp | Function | objectExpected error matcher.
messagestring | ErrorFailure detail.

Return Value

undefined

Returns normally or throws an assertion failure.

Working Example

Example Snippetnodejs
import assert from 'node:assert/strict';assert.throws(() => JSON.parse('{'), SyntaxError);console.log('matched');try {    assert.throws(() => 42);}catch (e) {    console.log(e.code);}
Node.js Reference