format.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2. /** @author Brian Cavalier */
  3. /** @author John Hann */
  4. (function(define) { 'use strict';
  5. define(function() {
  6. return {
  7. formatError: formatError,
  8. formatObject: formatObject,
  9. tryStringify: tryStringify
  10. };
  11. /**
  12. * Format an error into a string. If e is an Error and has a stack property,
  13. * it's returned. Otherwise, e is formatted using formatObject, with a
  14. * warning added about e not being a proper Error.
  15. * @param {*} e
  16. * @returns {String} formatted string, suitable for output to developers
  17. */
  18. function formatError(e) {
  19. var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
  20. return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
  21. }
  22. /**
  23. * Format an object, detecting "plain" objects and running them through
  24. * JSON.stringify if possible.
  25. * @param {Object} o
  26. * @returns {string}
  27. */
  28. function formatObject(o) {
  29. var s = String(o);
  30. if(s === '[object Object]' && typeof JSON !== 'undefined') {
  31. s = tryStringify(o, s);
  32. }
  33. return s;
  34. }
  35. /**
  36. * Try to return the result of JSON.stringify(x). If that fails, return
  37. * defaultValue
  38. * @param {*} x
  39. * @param {*} defaultValue
  40. * @returns {String|*} JSON.stringify(x) or defaultValue
  41. */
  42. function tryStringify(x, defaultValue) {
  43. try {
  44. return JSON.stringify(x);
  45. } catch(e) {
  46. return defaultValue;
  47. }
  48. }
  49. });
  50. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));