I have an error in my app: JSON.stringify cannot serialize cyclic structures. And I need to catch it. For it, I decided to override the JSON.stringify method with replacer that prints in the console the object with a circular reference like this:
const isCyclic = (obj: any): any => {
let keys: any[] = [];
let stack: any[] = [];
let stackSet = new Set();
let detected = false;
function detect(obj: any, key: any) {
if (obj && typeof obj != 'object') { return; }
if (stackSet.has(obj)) { // it's cyclic! Print the object and its locations.
let oldindex = stack.indexOf(obj);
let l1 = keys.join('.') + '.' + key;
let l2 = keys.slice(0, oldindex + 1).join('.');
console.log('CIRCULAR: ' + l1 + ' = ' + l2 + ' = ' + obj);
console.log(obj);
detected = true;
return;
}
keys.push(key);
stack.push(obj);
stackSet.add(obj);
for (var k in obj) { //dive on the object's children
if (Object.prototype.hasOwnProperty.call(obj, k)) { detect(obj[k], k); }
}
keys.pop();
stack.pop();
stackSet.delete(obj);
return;
}
detect(obj, 'obj');
return detected;
};
const originalStringify = JSON.stringify;
JSON.stringify = (value: any) => {
return originalStringify(value, isCyclic(value));
};
And now I need to change it with try/catch that can throw an error with the caught object with the circular references. Can you recommend the best way how can I change my function, please?