33 Like JSON.stringify, but doesn't throw on circular references.
44
55 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.
88
99 ISC license: https://github.com/isaacs/json-stringify-safe/blob/master/LICENSE
1010*/
@@ -23,24 +23,52 @@ function stringify(obj, replacer, spaces, cycleReplacer) {
2323 return JSON . stringify ( obj , serializer ( replacer , cycleReplacer ) , spaces ) ;
2424}
2525
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+
2644function serializer ( replacer , cycleReplacer ) {
27- var stack = [ ] ,
28- keys = [ ] ;
45+ var stack = [ ] ;
46+ var keys = [ ] ;
2947
30- if ( cycleReplacer == null )
48+ if ( cycleReplacer == null ) {
3149 cycleReplacer = function ( key , value ) {
32- if ( stack [ 0 ] === value ) return '[Circular ~]' ;
50+ if ( stack [ 0 ] === value ) {
51+ return '[Circular ~]' ;
52+ }
3353 return '[Circular ~.' + keys . slice ( 0 , indexOf ( stack , value ) ) . join ( '.' ) + ']' ;
3454 } ;
55+ }
3556
3657 return function ( key , value ) {
3758 if ( stack . length > 0 ) {
3859 var thisPos = indexOf ( stack , this ) ;
3960 ~ thisPos ? stack . splice ( thisPos + 1 ) : stack . push ( this ) ;
4061 ~ 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 ) ;
4362
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 ) ;
4573 } ;
4674}
0 commit comments