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

后端 未结 11 2319
心在旅途
心在旅途 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:37

    You can solve this with a one-liner( errStringified ) in plain javascript:

    var error = new Error('simple error message');
    var errStringified = (err => JSON.stringify(Object.getOwnPropertyNames(Object.getPrototypeOf(err)).reduce(function(accumulator, currentValue) { return accumulator[currentValue] = err[currentValue], accumulator}, {})))(error);
    console.log(errStringified);
    

    It works with DOMExceptions as well.

提交回复
热议问题