Skip to content

Instantly share code, notes, and snippets.

@jmaicaaan
Created March 31, 2021 13:25
Show Gist options
  • Save jmaicaaan/ba0f0a42e98937705582163a4e215fbc to your computer and use it in GitHub Desktop.
Save jmaicaaan/ba0f0a42e98937705582163a4e215fbc to your computer and use it in GitHub Desktop.
[Tutorial] Functional try catch
const getData = (id) => {
if (!id) {
throw new Error('No id found');
}
return [1, 2, 3, 4, 5].filter(i => i % id);
};
const tryCatch = (tryer) => {
try {
const result = tryer();
return [result, null];
} catch (error) {
return [null, error];
}
};
const demo03 = () => {
const [data, err] = tryCatch(() => getData(2));
if (data.includes(1)) {
console.log('data', data); // [1, 3, 5]
}
};
demo03();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment