Files
lodash/utility/attempt.js
John-David Dalton f9606b394c Bump to v3.0.0.
2015-02-04 00:38:56 -08:00

32 lines
651 B
JavaScript

var isError = require('../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);
}
}
module.exports = attempt;