0

The following code uses a boolean preference active: In the active state, it does an operation which could throw an exception. On this exception, it does fall back to the non-active state.

let active = somePreference;
function getValue(parameter) {
    try {
        if ( active ) {
            return valueStore.query(parameter);
        } else {
            throw {name: 'MyException'};
        }
    } catch (e) {
        return getRandomValue();
    }
}

This function can be called several times a second. The valueStore returns a positive value on success and throws an exception on failure. (as recommended f.ex. by Exception versus return code in DAO pattern).

An alternative would be an external if..else block to avoid the second exception, but which would have some code duplication.

How to write clean code with an exception and a condition both triggering the same action? In JavaScript, that is.

Related:

2

You could turn things inside out like this:

function getValue(parameter) {
    if (active) {
        try {
            return valueStore.query(parameter)
        } catch (e) {
            // quietly fall back to non-active behavior
        }
    }

    return getRandomValue();
}

Now there's no duplication or local exceptions. Should the fall back logic (getRandomValue()) fail, you'd always get an exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.