HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Attempt invoking a JavaScript function

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptinvokingattemptfunction

Problem

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.

Solution

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 = []

Code Snippets

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 = []

Context

From 30-seconds-of-code: attempt-invoking-function

Revisions (0)

No revisions yet.