3
3
Like JSON.stringify, but doesn't throw on circular references.
4
4
5
5
Originally forked from https://github.com/isaacs/json-stringify-safe
6
- version 5.0.1 on 3/8/2017 and modified for IE8 compatibility.
7
- Tests for this are in test/vendor.
6
+ version 5.0.1 on 3/8/2017 and modified to handle Errors serialization
7
+ and IE8 compatibility. Tests for this are in test/vendor.
8
8
9
9
ISC license: https://github.com/isaacs/json-stringify-safe/blob/master/LICENSE
10
10
*/
@@ -23,24 +23,52 @@ function stringify(obj, replacer, spaces, cycleReplacer) {
23
23
return JSON . stringify ( obj , serializer ( replacer , cycleReplacer ) , spaces ) ;
24
24
}
25
25
26
+ // https://github.com/ftlabs/js-abbreviate/blob/fa709e5f139e7770a71827b1893f22418097fbda/index.js#L95-L106
27
+ function stringifyError ( value ) {
28
+ var err = {
29
+ // These properties are implemented as magical getters and don't show up in for in
30
+ stack : value . stack ,
31
+ message : value . message ,
32
+ name : value . name
33
+ } ;
34
+
35
+ for ( var i in value ) {
36
+ if ( Object . prototype . hasOwnProperty . call ( value , i ) ) {
37
+ err [ i ] = value [ i ] ;
38
+ }
39
+ }
40
+
41
+ return err ;
42
+ }
43
+
26
44
function serializer ( replacer , cycleReplacer ) {
27
- var stack = [ ] ,
28
- keys = [ ] ;
45
+ var stack = [ ] ;
46
+ var keys = [ ] ;
29
47
30
- if ( cycleReplacer == null )
48
+ if ( cycleReplacer == null ) {
31
49
cycleReplacer = function ( key , value ) {
32
- if ( stack [ 0 ] === value ) return '[Circular ~]' ;
50
+ if ( stack [ 0 ] === value ) {
51
+ return '[Circular ~]' ;
52
+ }
33
53
return '[Circular ~.' + keys . slice ( 0 , indexOf ( stack , value ) ) . join ( '.' ) + ']' ;
34
54
} ;
55
+ }
35
56
36
57
return function ( key , value ) {
37
58
if ( stack . length > 0 ) {
38
59
var thisPos = indexOf ( stack , this ) ;
39
60
~ thisPos ? stack . splice ( thisPos + 1 ) : stack . push ( this ) ;
40
61
~ thisPos ? keys . splice ( thisPos , Infinity , key ) : keys . push ( key ) ;
41
- if ( ~ indexOf ( stack , value ) ) value = cycleReplacer . call ( this , key , value ) ;
42
- } else stack . push ( value ) ;
43
62
44
- return replacer == null ? value : replacer . call ( this , key , value ) ;
63
+ if ( ~ indexOf ( stack , value ) ) {
64
+ value = cycleReplacer . call ( this , key , value ) ;
65
+ }
66
+ } else {
67
+ stack . push ( value ) ;
68
+ }
69
+
70
+ return replacer == null
71
+ ? value instanceof Error ? stringifyError ( value ) : value
72
+ : replacer . call ( this , key , value ) ;
45
73
} ;
46
74
}
0 commit comments