Files
30-seconds-of-code/snippets/attempt.md
Angelos Chalaris 8a6b73bd0c Update covers
2023-02-16 22:24:28 +02:00

770 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Attempt invoking a function function spanish-resort 2018-01-28T14:44:40+02:00 2020-10-18T20:24:28+03:00

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.
  • If the caught object is not an 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 = []