attempt.js 931 B

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