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:

asked May 2, 2016 at 6:31
0

1 Answer 1

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.

answered May 2, 2016 at 15:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.