【发布时间】:2019-12-26 07:52:02
【问题描述】:
我的应用程序出现错误:JSON.stringify 无法序列化循环结构。我需要抓住它。为此,我决定使用替换器覆盖 JSON.stringify 方法,该替换器在控制台中使用循环引用打印对象,如下所示:
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));
};
现在我需要使用 try/catch 对其进行更改,这可能会引发带有循环引用的捕获对象的错误。你能推荐我如何改变我的功能的最佳方法吗?
【问题讨论】:
标签: javascript json object try-catch circular-reference