771 B
771 B
title, type, language, tags, cover, dateModified
| title | type | language | tags | cover | dateModified | |
|---|---|---|---|---|---|---|
| Attempt invoking a function | snippet | javascript |
|
spanish-resort | 2020-10-18T20:24:28+03:00 |
Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.
- Use a
try...catchblock to return either the result of the function or an appropriate error. - If the caught object is not an
Error, use it to create a newError.
const attempt = (fn, ...args) => {
try {
return fn(...args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
};
var elements = attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) elements = []; // elements = []