0
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?

Jack
  • 13
  • 1
  • It's not possible to say given that nowhere in the code you posted is a call to `JSON.stringify()`. Not all object structures can be serialized as JSON. – Pointy Mar 21 '20 at 01:30

1 Answers1

2

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.

Jacob
  • 77,566
  • 24
  • 149
  • 228
  • that is, you need to check for an object? – Jack Mar 21 '20 at 01:34
  • No, it has nothing to do with that; the issue is that if you are walking through properties, and some property refers to something already encountered earlier, then you'll loop indefinitely. For example, imagine trying to serialize the object `const a = { name: 'a' }; const b = { name: 'b', parent: a }; a.child = b;`. The serializer would go through the pattern `{ "name": "a", "child": { "name": "b", "parent": { "name": "a", "child": { "name": "b", "parent"...` and so forth without terminating until running out of memory or overflowing the stack. – Jacob Mar 21 '20 at 01:37
  • 1
    Note that other serialization pitfalls also exist, like serializing huge buffers, certificate chains, etc. Basically, long story short, it's usually a bad idea to serialize any object of an unknown shape. I see this problem _especially_ with error objects that carry with them tons of details like HTTP request and response objects. – Jacob Mar 21 '20 at 01:39
  • Now it’s clear, I found a solution to get the necessary parameters manually. Thanks – Jack Mar 21 '20 at 01:43