Is it not possible to stringify an Error using JSON.stringify?

后端 未结 11 2390
心在旅途
心在旅途 2020-11-22 07:54

Reproducing the problem

I\'m running into an issue when trying to pass error messages around using web sockets. I can replicate the issue I am facing using J

11条回答
  •  忘掉有多难
    2020-11-22 08:47

    None of the answers above seemed to properly serialize properties which are on the prototype of Error (because getOwnPropertyNames() does not include inherited properties). I was also not able to redefine the properties like one of the answers suggested.

    This is the solution I came up with - it uses lodash but you could replace lodash with generic versions of those functions.

     function recursivePropertyFinder(obj){
        if( obj === Object.prototype){
            return {};
        }else{
            return _.reduce(Object.getOwnPropertyNames(obj), 
                function copy(result, value, key) {
                    if( !_.isFunction(obj[value])){
                        if( _.isObject(obj[value])){
                            result[value] = recursivePropertyFinder(obj[value]);
                        }else{
                            result[value] = obj[value];
                        }
                    }
                    return result;
                }, recursivePropertyFinder(Object.getPrototypeOf(obj)));
        }
    }
    
    
    Error.prototype.toJSON = function(){
        return recursivePropertyFinder(this);
    }
    

    Here's the test I did in Chrome:

    var myError = Error('hello');
    myError.causedBy = Error('error2');
    myError.causedBy.causedBy = Error('error3');
    myError.causedBy.causedBy.displayed = true;
    JSON.stringify(myError);
    
    {"name":"Error","message":"hello","stack":"Error: hello\n    at :66:15","causedBy":{"name":"Error","message":"error2","stack":"Error: error2\n    at :67:20","causedBy":{"name":"Error","message":"error3","stack":"Error: error3\n    at :68:29","displayed":true}}}  
    

提交回复
热议问题