Files
lodash/utility/attempt.js
John-David Dalton 5379c1996b Bump to v3.0.0.
2015-01-25 13:44:01 -08:00

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;