Brilliant way to check errors and edge cases in function without really checking at all. We just wrap the function into try...catch block and return default value from catch If function already exists just put it into wrapper Example
function sum(params) {
try {
return params.numbers.a + params.numbers.b
} catch (error) {
console.log(error)
return 'no value for you'
}
}
sum({ numbers: { a: 1, b: 2 } }) // 3
sum({ a: 1, b: 2 }) // no value for you
getValueOrDefault wrapper
const getValueOrDefault = (getter, defaultValue) => {
try {
return getter()
} catch (error) {
console.log(error)
return defaultValue
}
}
function substract(params) {
return params.numbers.a - params.numbers.b
}
getValueOrDefault(() => substract({ numbers: { a: 1, b: 2 } }), 'no value for you') // -1
getValueOrDefault(() => substract({ a: 1, b: 2 }), 'no value for you') // no value for you