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

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

    Make it serializable

    // example error
    let err = new Error('I errored')
    
    // one liner converting Error into regular object that can be stringified
    err = Object.getOwnPropertyNames(err).reduce((acc, key) => { acc[key] = err[key]; return acc; }, {})
    

    If you want to send this object from child process, worker or though the network there's no need to stringify. It will be automatically stringified and parsed like any other normal object

提交回复
热议问题