Feedback appreciated
Synopsis
Provide a standardized way to assert that an expression is true.
Motivation
Developers often want to ensure a condition is met before allowing their program to proceed. There is currently no standardized way to do this independent from the host environment other than manually checking if an expression is true
and conditionally throwing, as demonstrated by this example:
if (user == null) {
throw new Error('User is not defined');
}
Prior Art
- Node's
assert
library, specificallyassert.ok
- Rust, Ruby, Python, Elixir, C++, Java, and many other languages have a built in
assert
function
Solution
The proposed solution is to add a class method to the intrinsic object Error
named assert
. This would allow the above example to be refactored into:
Error.assert(user != null, 'User is not defined');
A shim for this would look like:
Error.assert = function(assertion, ...rest) {
if (!assertion) {
throw new this(...rest)
}
}
The other core error constructors that inherit from Error
could then also be used in a similar fashion:
TypeError.assert(user != null, 'User is not defined');