30秒学会 JavaScript 片段 · 2022年11月22日

30秒学会 JavaScript 片段 – Attempt invoking a function

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);
  }
};

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

翻译自:https://www.30secondsofcode.org/js/s/attempt-invoking-function