0

Say I have some code like this:

function a() {
    console.log("A is all good"); 
}

function b() {
    console.log("B throws an error"); 
    throw new Error ("I am an error that comes from B"); 
}

function c() {
    console.log("C is all good."); 
}


function run() {
    try {
        a(); 
        b(); 
        c(); 
    } catch(err) {
        throw new Error ("An error occur in the run function."); 
    }
}

run(); 

(Unfortunately Stack Overflow doesn't play very well with stack traces, so my snippet will be a little unclear).

The problem with this code is that when that error throws from run() I lose details of which function it was that cause that error to throw.

How can I include the stack trace of caught error into the thrown error?

Edit: - This question asks specifically about extending an error. While the dupe linked answer provides helpful details - it doesn't contain the specific question (Which I now have an answer for). I'd appreciate reopening the question so I can post my answer.

dwjohnston
  • 11,163
  • 32
  • 99
  • 194
  • Just access the `stack` property of the `err` to get the stack trace - then you can include it in the next thrown error, maybe `throw new Error ("An error occur in the run function:\n" + err.stack + '\n');` – CertainPerformance Sep 18 '19 at 04:35
  • In the catch statement `catch( err){...}` in `run`, log the error caught `console.log("error caught in run(): ", err)` At least Firefox and Chrome expand the error object's stack information for you. – traktor Oct 19 '19 at 02:58

0 Answers0