简体   繁体   English

如何使用替换器在 JSON.stringify 中使用 try/catch 捕获错误?

[英]How to catch an error with try/catch in JSON.stringify with replacer?

I have an error in my app: JSON.stringify cannot serialize cyclic structures.我的应用程序中出现错误:JSON.stringify 无法序列化循环结构。 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:为此,我决定使用替换器覆盖 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));
};

And now I need to change it with try/catch that can throw an error with the caught object with the circular references.现在我需要用 try/catch 来改变它,它可以用循环引用捕获的对象抛出错误。 Can you recommend the best way how can I change my function, please?你能推荐我如何改变我的功能的最佳方式吗?

Do I understand correctly, that you want to throw a custom error and consume this error with a function that is recursive?我是否理解正确,您想抛出自定义错误并使用递归函数消耗此错误?

Btw don't run this code...顺便说一句,不要运行此代码...

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)
    }
}

You can throw an error from a try block into a following catch block and you could also nest them but this is an abomination.您可以将错误从 try 块抛出到下一个 catch 块中,也可以嵌套它们,但这是可憎的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM