Blame view

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