errors.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /* eslint no-undefined: 0 */
  2. 'use strict';
  3. const format = require('./format');
  4. const { LEVEL, MESSAGE } = require('triple-beam');
  5. /*
  6. * function errors (info)
  7. * If the `message` property of the `info` object is an instance of `Error`,
  8. * replace the `Error` object its own `message` property.
  9. *
  10. * Optionally, the Error's `stack` and/or `cause` properties can also be appended to the `info` object.
  11. */
  12. module.exports = format((einfo, { stack, cause }) => {
  13. if (einfo instanceof Error) {
  14. const info = Object.assign({}, einfo, {
  15. level: einfo.level,
  16. [LEVEL]: einfo[LEVEL] || einfo.level,
  17. message: einfo.message,
  18. [MESSAGE]: einfo[MESSAGE] || einfo.message
  19. });
  20. if (stack) info.stack = einfo.stack;
  21. if (cause) info.cause = einfo.cause;
  22. return info;
  23. }
  24. if (!(einfo.message instanceof Error)) return einfo;
  25. // Assign all enumerable properties and the
  26. // message property from the error provided.
  27. const err = einfo.message;
  28. Object.assign(einfo, err);
  29. einfo.message = err.message;
  30. einfo[MESSAGE] = err.message;
  31. // Assign the stack and/or cause if requested.
  32. if (stack) einfo.stack = err.stack;
  33. if (cause) einfo.cause = err.cause;
  34. return einfo;
  35. });