Home Reference Source

ts_temp/function/tryCatch.js

  1. import curryN from './curryN';
  2. /**
  3. * Takes two functions, tryer and catcher.
  4. *
  5. * Returns a function that, when invoked with zero or more parameters,
  6. * calls the tryer with those parameters, and if tryer throws,
  7. * calls the catcher with the error as first argument and original arguments as rest.
  8. * If that still throws, then ¯\_(ツ)_/¯
  9. *
  10. * @param {Function} tryer
  11. * @param {Function} catcher
  12. * @return {Function}
  13. * @example
  14. * tryCatch(x => x.length, () => 0)([ 1, 2, 3 ]) // 3
  15. * tryCatch(x => x.length, () => 0)( undefined ) // 0
  16. * tryCatch(
  17. * someDataTransform,
  18. * (err, ...rest) => {
  19. * logAsyncToServer('someDataTransform failed', err, 'with arguments', rest);
  20. * return DEFAULT_VALUE;
  21. * }
  22. * )( someIncompleteData ) // DEFAULT_VALUE (error is logged somewhere)
  23. */
  24. export default curryN(2, (tryer, catcher) => {
  25. return (...args) => {
  26. try {
  27. return tryer.apply(this, args);
  28. }
  29. catch (e) {
  30. args.unshift(e);
  31. return catcher.apply(this, args);
  32. }
  33. };
  34. });