Javascript: getting the name of the calling function

I am writing an error event handler that captures the error and makes an ajax call to the server to report it. The problem is that many 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, if the window.onerror event is triggered on CalledVeryOften, it is possible that the parameters might not be computed correctly.

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

Thank.

+3


source to share


1 answer


The caller's name can be obtained through the deprecated arguments.callee.caller.name

MDN:arguments.callee

property .

Another method is to parse the value new Error().stack

.



In Chrome, you can use:

var stackTrace = {};
Error.captureStackTrace(stackTrace); // Get the stack trace
stackTrace = stackTrace.stack;       // Formatted string

      

+2


source







All Articles