iferr.js 837 B

1234567891011121314151617181920212223
  1. // Delegates to `succ` on sucecss or to `fail` on error
  2. // ex: Thing.load(123, iferr(cb, thing => ...))
  3. const iferr = (fail, succ) => (err, ...a) => err ? fail(err) : succ(...a)
  4. // Like iferr, but also catches errors thrown from `succ` and passes to `fail`
  5. const tiferr = (fail, succ) => iferr(fail, (...a) => {
  6. try { succ(...a) }
  7. catch (err) { fail(err) }
  8. })
  9. // Delegate to the success function on success, throws the error otherwise
  10. // ex: Thing.load(123, throwerr(thing => ...))
  11. const throwerr = iferr.bind(null, err => { throw err })
  12. // Prints errors when one is passed, or does nothing otherwise
  13. // ex: Thing.load(123, printerr)
  14. const printerr = iferr(err => console.error(err), () => {})
  15. module.exports = exports = iferr
  16. exports.iferr = iferr
  17. exports.tiferr = tiferr
  18. exports.throwerr = throwerr
  19. exports.printerr = printerr