Skip to content
Advertisement

How to continue running functions down the chain if an error threw?

So, I should create some functions with chains for validating, example:

isValid('Test string').required().isString().min(5);

and function should throw an error if something isn’t comparing.

I have a problem, if something throw an error, than it doesn’t continue work, I tried to add try catch, but then tests shows me that it don’t throw an error. I want to pass test with .toThrowError() and continue chaining

function isValid(str) {

  return {
    required: function() {
        if (str === '') {
          console.log("dasdsada2",str, this)
          throw new Error('Required!');
        }
        return this;
    },
    isString: () => {
        if (typeof str !== 'string') {
          throw new Error('Should be a string!');
        }
        return this;
    },
    min: (minNum) => {
        if (str.length < minNum) {
          throw new Error('Should be more than min'); 
        }
        return this;
    }
  };  
}

Advertisement

Answer

You can make a function that wraps all the functions with a wrapper that catches errors and stores them in an array, then a method that will throw all the errors together at the end:

function wrapErrors(obj) {
    const errors = [];
    const ret = {};
    for (const key in obj) {
        const func = obj[key];
        ret[key] = function() {
            try {
                func.apply(this, arguments);
            } catch (err) {
                errors.push(err.message);
            }
            return this;
        };
    }
    ret.throwErrors = function() {
        if (errors.length > 0) {
            throw new Error("Got errors: " + errors.join(", "));
        }
        return this;
    };
    return ret;
}

// throws nothing
wrapErrors(isValid('Test string')).required().isString().min(5).throwErrors(); 
// throws 'Got errors: Required!, Should be more than min'
wrapErrors(isValid('')).required().isString().min(5).throwErrors(); 
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement