UNPKG

929 BJavaScriptView Raw
1import apply from './_apply.js';
2import baseRest from './_baseRest.js';
3import isError from './isError.js';
4
5/**
6 * Attempts to invoke `func`, returning either the result or the caught error
7 * object. Any additional arguments are provided to `func` when it's invoked.
8 *
9 * @static
10 * @memberOf _
11 * @since 3.0.0
12 * @category Util
13 * @param {Function} func The function to attempt.
14 * @param {...*} [args] The arguments to invoke `func` with.
15 * @returns {*} Returns the `func` result or error object.
16 * @example
17 *
18 * // Avoid throwing errors for invalid selectors.
19 * var elements = _.attempt(function(selector) {
20 * return document.querySelectorAll(selector);
21 * }, '>_>');
22 *
23 * if (_.isError(elements)) {
24 * elements = [];
25 * }
26 */
27var attempt = baseRest(function(func, args) {
28 try {
29 return apply(func, undefined, args);
30 } catch (e) {
31 return isError(e) ? e : new Error(e);
32 }
33});
34
35export default attempt;