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

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

    We needed to serialise an arbitrary object hierarchy, where the root or any of the nested properties in the hierarchy could be instances of Error.

    Our solution was to use the replacer param of JSON.stringify(), e.g.:

    function jsonFriendlyErrorReplacer(key, value) {
      if (value instanceof Error) {
        return {
          // Pull all enumerable properties, supporting properties on custom Errors
          ...value,
          // Explicitly pull Error's non-enumerable properties
          name: value.name,
          message: value.message,
          stack: value.stack,
        }
      }
    
      return value
    }
    
    let obj = {
        error: new Error('nested error message')
    }
    
    console.log('Result WITHOUT custom replacer:', JSON.stringify(obj))
    console.log('Result WITH custom replacer:', JSON.stringify(obj, jsonFriendlyErrorReplacer))

提交回复
热议问题