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

问题描述 投票:-1回答:1

我的应用出现错误:JSON.stringify无法序列化循环结构。我需要抓住它。为此,我决定用replacer覆盖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个回答
0
投票

我是否正确理解,您想引发自定义错误并使用递归函数消耗此错误?

© www.soinside.com 2019 - 2024. All rights reserved.