javascripterror-handlinginvariants

Using Facebook's invariant vs if throw


I've been looking at various Node.js projects' source, and I've noticed that some people use invariant. From what I understood, invariant is a tool that lets you put assertions in your code, and raise errors as needed.

Question:

When would you favor using invariant vs throwing errors the traditional way?

// Using invariant
function doSomething(a, b) {
   invariant(a > b, 'A should be greater than B');
}

// If throw
function doSomething(a, b) {
   if(a <= b) {
      throw new Error('A should be greater than B');
   }
}

Solution

  • There are a few reasons:


    function f(xs, x) {
        // all the invariants are lined up, one after another
        invariant(xs.type == x.type, "adding an element with the same type");
        invariant(xs.length != LIST_MAX_SIZE, "the list isn't full");
        invariant(fitting(x), "x is fitting right in the list");
    }
    

    Compare with the usual throw approach:

    function f(xs, x) {
        if (xs.type != x.type)
           throw new Error("adding an element with the same type");
        if (xs.length == LIST_MAX_SIZE)
           throw new Error("the list isn't full");
        if (!fitting(x))
           throw new Error("x is fitting right in the list");
    }