Sometimes there is a need to call a function and handle the exception directly (with a try/catch), and other times there it is preferable to call the same function and receive a null
or false
if it would otherwise fail.
This idea or use-case is similar to Rails in ActiveRecord where you have a choice of calling User.find(1)
or User.find!(1)
— the former will return nil
if not found and the latter will raise an exception.
Question: I am the author of these functions so I can design this in any way. Is there a prescribed pattern in javascript for this idea?
One idea is to just mimic what is done in ActiveRecord:
// returns API data or bubbles-up exception
function getDataFromAPI() {
const response = callApi(); // function throws error if not 200
return response.data;
}
// returns API data or null
function getDataFromAPI_() {
try {
return getDataFromAPI();
} catch(e) {
return null;
}
}
Maybe another way is to create a generic wrapper for the try/catch, though this example doesn't account for arguments:
// returns API data, but will raise an exception if
// `response` has no `data` property...
function getDataFromAPI() {
const response = callApi();
return response.data;
}
// return function or null
function nullIfError(func) {
try {
return func();
} catch(e) {
return null;
}
}
nullIfError(getDataFromAPI)
Or, add a parameter to conditially change it the behavior, but I don't like that it's always wrapped in a try/catch...
function getDataFromAPI(throwError = true) {
try {
const response = callApi();
return response.data;
} catch(e) {
if (throwError) throw(e);
else return null;
}
}