Error.assert

Feedback appreciated :pray:

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, specifically assert.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');
4 Likes

Props to @NilSet who also helped ideate this.

most environments have console.assert, which does basically what you're asking. it's not part of js itself but it is everything that follows the console specification.

1 Like

The main issue with console.assert is that it does not throw and only prints to the console. In the below example 'bar' is not logged.

try {
  console.assert(false, 'foo');
} catch(e) {
  console.log('bar');
}
// Assertion failed: foo
1 Like