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