0 day streak
javascript / intermediate
Snippet

Internal State Validation with Node.js Assert

The 'node:assert' module provides functions for verifying internal invariants. While not a replacement for user input validation, it is essential for defensive programming to ensure that logic assumptions remain true during execution.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import assert from 'node:assert';
function processOrder(price, quantity) {
assert(typeof price === 'number', 'Price must be a number');
assert(quantity > 0, 'Quantity must be at least 1');
const total = price * quantity;
assert.strictEqual(total, price * quantity, 'Calculation integrity failure');
return total;
}
try {
processOrder(19.99, -1);
} catch (err) {
console.log('Validation failed:', err.message);
}
nodejs
Breakdown
1
import assert from 'node:assert';
Imports the built-in assertion module for Node.js.
2
assert(condition, message);
Throws an AssertionError if the condition evaluates to false.
3
assert.strictEqual(a, b, msg);
Ensures that two values are identical using strict equality (===).