Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: getting the name of the calling function

Tags:

javascript

I'm writing an error event handler that captures an error and makes an AJAX call to the server to report it. The problem is that a lot of times, my code looks like this:

function A() {

  //lots of works to calculate SomeParameters; can bug
  CalledVeryOften(SomeParameters);
}

function CalledVeryOften(SomeParameters) {
  // a little bit of work
}

If I capture the event in function A (or B, C, D...), great! But the problem is that if the window.onerror event fires in CalledVeryOften then it might be that the parameters might not be properly calculated.

Is there a way in CalledVeryOften to determine which function it was called from?

like image 737
frenchie Avatar asked Sep 25 '26 13:09

frenchie


1 Answers

The name of the calling function can be obtained via the deprecated arguments.callee.caller.name property MDN: arguments.callee.

Another method is by parsing the value of new Error().stack.

In Chrome you can use:

var stackTrace = {};
Error.captureStackTrace(stackTrace); // Get the stack trace
stackTrace = stackTrace.stack;       // Formatted string
like image 64
Rob W Avatar answered Sep 27 '26 04:09

Rob W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!