Aller au contenu principal

Invariant

Throw descriptive error in development, generic error in production.

API

Motivation

This package provides a simple way to throw error from an assertion and a message. It is built to be easily parsed / minified at compile time.

Usage

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
}

Coding Guide

attention

Use invariant with caution

In general, throwing errors is discouraged, instead Result should be used.

See explanation

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}}'
);

FAQ