tryCatch.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import _arity from "./internal/_arity.js";
  2. import _concat from "./internal/_concat.js";
  3. import _curry2 from "./internal/_curry2.js";
  4. /**
  5. * `tryCatch` takes two functions, a `tryer` and a `catcher`. The returned
  6. * function evaluates the `tryer`; if it does not throw, it simply returns the
  7. * result. If the `tryer` *does* throw, the returned function evaluates the
  8. * `catcher` function and returns its result. Note that for effective
  9. * composition with this function, both the `tryer` and `catcher` functions
  10. * must return the same type of results.
  11. *
  12. * @func
  13. * @memberOf R
  14. * @since v0.20.0
  15. * @category Function
  16. * @sig (...x -> a) -> ((e, ...x) -> a) -> (...x -> a)
  17. * @param {Function} tryer The function that may throw.
  18. * @param {Function} catcher The function that will be evaluated if `tryer` throws.
  19. * @return {Function} A new function that will catch exceptions and send them to the catcher.
  20. * @example
  21. *
  22. * R.tryCatch(R.prop('x'), R.F)({x: true}); //=> true
  23. * R.tryCatch(() => { throw 'foo'}, R.always('caught'))('bar') // =>
  24. * 'caught'
  25. * R.tryCatch(R.times(R.identity), R.always([]))('s') // => []
  26. * R.tryCatch(() => { throw 'this is not a valid value'}, (err, value)=>({error : err, value }))('bar') // => {'error': 'this is not a valid value', 'value': 'bar'}
  27. */
  28. var tryCatch =
  29. /*#__PURE__*/
  30. _curry2(function _tryCatch(tryer, catcher) {
  31. return _arity(tryer.length, function () {
  32. try {
  33. return tryer.apply(this, arguments);
  34. } catch (e) {
  35. return catcher.apply(this, _concat([e], arguments));
  36. }
  37. });
  38. });
  39. export default tryCatch;