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
| Name | Type | Description |
|---|---|---|
| fn | Function | Operation expected to throw. |
| error | RegExp | Function | object | Expected error matcher. |
| message | string | Error | Failure 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);}