Javascript 如何在JSON.stringify with replacer中使用try/catch捕捉错误?
我的应用程序中有一个错误:JSON.stringify无法序列化循环结构。我需要抓住它。为此,我决定使用replacer覆盖JSON.stringify方法,该方法在控制台中打印具有如下循环引用的对象:Javascript 如何在JSON.stringify with replacer中使用try/catch捕捉错误?,javascript,json,object,try-catch,circular-reference,Javascript,Json,Object,Try Catch,Circular Reference,我的应用程序中有一个错误:JSON.stringify无法序列化循环结构。我需要抓住它。为此,我决定使用replacer覆盖JSON.stringify方法,该方法在控制台中打印具有如下循环引用的对象: const isCyclic = (obj: any): any => { let keys: any[] = []; let stack: any[] = []; let stackSet = new Set(); let detected = false; fun
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来更改它,它可以对带有循环引用的捕获对象抛出错误。您能推荐一种最好的方法来更改我的函数吗?我是否正确理解,您希望抛出一个自定义错误,并使用递归函数使用此错误 顺便说一句,不要运行此代码
const err = {
no: 1,
msg: 'simple error'
}
function recusiveErrors(err){
try{
console.log(`getting rdy to throw`)
// throwing
throw err
} catch(error){
// catching and calling recursivel
recusiveErrors(error)
}
}
您可以将try块中的错误抛出到下面的catch块中,也可以嵌套它们,但这是一个令人讨厌的问题