【问题标题】:How to catch an error with try/catch in JSON.stringify with replacer?如何使用替换器在 JSON.stringify 中使用 try/catch 捕获错误?
【发布时间】: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


    【解决方案1】:

    我是否理解正确,您想抛出自定义错误并使用递归函数处理此错误?

    顺便说一句,不要运行此代码...

    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 块中,也可以嵌套它们,但这是可恶的。

    【讨论】:

      猜你喜欢
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 2019-01-12
      • 2021-10-08
      • 2013-07-18
      • 1970-01-01
      相关资源
      最近更新 更多