mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-01 07:47:49 +00:00
32 lines
646 B
JavaScript
32 lines
646 B
JavaScript
import isError from '../lang/isError';
|
|
|
|
/**
|
|
* Attempts to invoke `func`, returning either the result or the caught
|
|
* error object.
|
|
*
|
|
* @static
|
|
* @memberOf _
|
|
* @category Utility
|
|
* @param {*} func The function to attempt.
|
|
* @returns {*} Returns the `func` result or error object.
|
|
* @example
|
|
*
|
|
* // avoid throwing errors for invalid selectors
|
|
* var elements = _.attempt(function() {
|
|
* return document.querySelectorAll(selector);
|
|
* });
|
|
*
|
|
* if (_.isError(elements)) {
|
|
* elements = [];
|
|
* }
|
|
*/
|
|
function attempt(func) {
|
|
try {
|
|
return func();
|
|
} catch(e) {
|
|
return isError(e) ? e : Error(e);
|
|
}
|
|
}
|
|
|
|
export default attempt;
|