-1

I have an error in my app: JSON.stringify cannot serialize cyclic structures. 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:

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. Can you recommend the best way how can I change my function, please?

I'm the man.
  • 207
  • 2
  • 13
jocoders
  • 1,594
  • 2
  • 19
  • 54

1 Answers1

0

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.

fubar
  • 383
  • 2
  • 11