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.

2
  • 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'); Commented Sep 18, 2019 at 4: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. Commented Oct 19, 2019 at 2:58

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.