attempt.js 839 B

1234567891011121314151617181920212223242526272829303132
  1. var isError = require('../lang/isError'),
  2. restParam = require('../function/restParam');
  3. /**
  4. * Attempts to invoke `func`, returning either the result or the caught error
  5. * object. Any additional arguments are provided to `func` when it's invoked.
  6. *
  7. * @static
  8. * @memberOf _
  9. * @category Utility
  10. * @param {Function} func The function to attempt.
  11. * @returns {*} Returns the `func` result or error object.
  12. * @example
  13. *
  14. * // avoid throwing errors for invalid selectors
  15. * var elements = _.attempt(function(selector) {
  16. * return document.querySelectorAll(selector);
  17. * }, '>_>');
  18. *
  19. * if (_.isError(elements)) {
  20. * elements = [];
  21. * }
  22. */
  23. var attempt = restParam(function(func, args) {
  24. try {
  25. return func.apply(undefined, args);
  26. } catch(e) {
  27. return isError(e) ? e : new Error(e);
  28. }
  29. });
  30. module.exports = attempt;