1

When I am printing helpful errors in my program, I want to print along the method name. So for example in the mock code below when console logging inside goodMorning, I want to embed the name 'goodMorning' or 'Hello.goodMorning' in the print out by calling a getMethodName function; the function now simply returns 'goodMorning' but I want it to return the name of whatever method it is called in (it may need to take some argument to do that).

const getMethodName = () => {
    return 'goodMorning'
}

class Hello {
  goodMorning () {
    console.log(`I am inside ${getMethodName()} method`)
  }
}

new Hello().goodMorning()
  • 2
    It is usually better to use `console.trace` (or other `console` methods that also provide stack) or `debugger` to do this. – Amadan Jun 22 '20 at 05:09
  • Does this answer your question? [Get function name in JavaScript](https://stackoverflow.com/questions/3178892/get-function-name-in-javascript) – sibabrat swain Jun 22 '20 at 05:12
  • 1
    @sibabratswain not it doesn't answer my question. The solutions suggested there doesn't work for ES6 class methods. – faint-hearted-fool Jun 22 '20 at 05:42
  • @user120242 I see an answer posted there (https://stackoverflow.com/a/27462108/10654418) that also partly answers this question. But I am looking for a much better answer for ES6 class methods, not just for a classless function. – faint-hearted-fool Jun 22 '20 at 05:48

1 Answers1

3

I hope this is what u r asking for

const getMethodName = () => {
  var functionName = new Error().stack.match(/at (.*?) /);
  return functionName[1]
}

class Hello {
  goodMorning() {
    console.log(`I am inside ${getMethodName()} method`)
  }
}

new Hello().goodMorning();

Better u can directly try capturing error without calling to any specific function

Karan
  • 12,059
  • 3
  • 24
  • 40
  • Thank you. `console.log(`I am inside ${new Error().stack.match(/at (.*?) /)[1]} method`)` seems to work, but I wish there was a more elegant solution – faint-hearted-fool Jun 22 '20 at 05:34
  • 2
    FYI the function she's asking for is actually the calling method, not the helper function, so the regex you want is actually `new Error().stack.match(/at .*?\n.*? at (.*?) /)` to get the second function in the call stack (the caller). – user120242 Jun 22 '20 at 05:35
  • Yes, `const getMethodName = () => new Error().stack.match(/at .*?\n.*? at (.*?) /)[1]` does exactly what I am looking for. This will do for now. Thanks once again. – faint-hearted-fool Jun 22 '20 at 05:40
  • @faint-hearted-fool this has some browser compatibility issues apparently. Please see dupe link for more information: specifically this answer: https://stackoverflow.com/a/47812770/120242 – user120242 Jun 22 '20 at 05:45