javascriptrecursionstringifygetpropertygetproperties

Why does an infinite recursion error appear while processing JSON.stringify


function repErr(key, value) {
  let error = {};
  Object.getOwnPropertyNames(value).forEach(function (key) {
      error[key] = value[key];
  });
  return error;
}

When I call JSON.stringify(err, repErr) i see an error too much recursion in console.
I have firefox 68 and I called debugger at each iteration and I saw that on the fourth pass it starts to add something like this to the object:

{
  0: 'h',
  1: 't',
  2: 't',
  3: 'p',
  // and etc
}

What is the reason and can it be fixed?


Solution

  • The object most likely contains cycles, where an object in the tree references another object, which eventually references that first object. I find this issue occurs a lot with errors like those from axios because the response object refers to a request object, and the request object has a reference to the response object.

    It's an irritating problem that often bites us. Thankfully, there are libraries like json-decycle and others to solve this problem by changing circular references to something that can be serialized without a stack overflow.