Stopping execution
APIThrow errors to stop execution with recoverable errors
Stopping execution with panic errors
warning
Use with caution. See explanation
panic(error)
is equivalent to throw error
statement.
But as a function, it has the advantages :
- it can be used as an expression (ex: in ternary operator)
- it can be used as a parameter (ex: as a callback)
- it has a better semantic, implying that the program should stop
import { panic } from '@w5s/error';
function unsafeAsNotNullable(value: unknown) {
return value ?? panic(new TypeError('Value must not be nullable'));
}
Stopping execution with a condition (assertion)
warning
Use with caution. See explanation
invariant
can be used to assert a condition. If the condition is false, it will throw an error with a descriptive message.
invariant(
condition,
// ✓ Describe what is wrong
// ✓ Add a hint on how to fix it
// ✓ Starts with upper case character
// ex: '"A" is not a valid integer', 'Unexpected parameter "foo_bar"', ...
'{{Invariant message}}'
);
Example
import { invariant } from '@w5s/error';
function program() {
invariant(true, 'This will not throw an error');
// -> nothing
invariant(false, 'This will throw an error');
// -> throw InvariantError { message: 'Input should not be null' } when input is null or undefined
//... do something with input
}
FAQ
warning
Use throw
with caution : when the program should be stopped
In general, throwing errors is discouraged, instead Result should be used.
Nevertheless, errors can be thrown when :
- Some condition is detected during runtime and the program cannot continue (i.e. assertion)
- Program is in an impossible logical state and should be stopped (i.e. panic)