try... catch
block to return either the result of the function or an appropriate error.Error
, use it to create a new Error
.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 = []
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️