Files
lodash/utility/attempt.js
John-David Dalton 9b7c4d6761 Bump to v3.0.0.
2015-05-19 22:25:55 -07:00

33 lines
707 B
JavaScript

define(['../lang/isError'], function(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);
}
}
return attempt;
});