Skip to content

Home

Attempt invoking a JavaScript function

While try...catch blocks are commonly used to handle errors, they're not particularly friendly to the functional programming style. Luckily, we can roll up our own utility function to make it easier to handle errors when invoking functions.

All that we need is a higher-order function that takes a function and its arguments. It then uses a try...catch block to return either the result of the function or an appropriate error object. If the caught object is not an Error, it creates a new 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.