forked from lodash/lodash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
attempt.js
31 lines (29 loc) · 828 Bytes
/
attempt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import apply from './.internal/apply.js'
import isError from './isError.js'
/**
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it's invoked.
*
* @since 3.0.0
* @category Util
* @param {Function} func The function to attempt.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // Avoid throwing errors for invalid selectors.
* const elements = attempt(selector =>
* document.querySelectorAll(selector), '>_>')
*
* if (isError(elements)) {
* elements = []
* }
*/
function attempt(func, ...args) {
try {
return apply(func, undefined, args)
} catch (e) {
return isError(e) ? e : new Error(e)
}
}
export default attempt