Skip to content

Home

Attempt invoking a function

Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.

const attempt = (fn, ...args) => {
  try {
    return fn(...args);
  } catch (e) {
    return e instanceof Error ? e : new Error(e);
  }
};

let elements = attempt(function(selector) {
  return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) elements = []; // elements = []

More like this

Start typing a keyphrase to see matching snippets.