Files
30-seconds-of-code/snippets/attempt.md
Angelos Chalaris 611729214a Snippet format update
To match the starter (for the migration)
2019-08-13 10:29:12 +03:00

589 B

title, tags
title tags
attempt function,intermediate

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

Use a try... catch block to return either the result of the function or an appropriate 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 = []