2

While writing a logger, accessing the name of functions is ideal. Unfortunately this is quite tricky with strict mode. I have resorted to passing log messages as errors such as :

log(new Error("Foobar")

and then slicing up the error.stack to suit. I have come across an issue where the helpful function name is skipped in the stack output.

// helpfulName.ts
export const helpfulName = ()=> wrapper(networkCallWithSimilarName())

// wrapper.ts
export async function* wrapper(generator){
log(new Error("Foobar")
return generator // I actually for of ... yield here
}

// index.ts

(async ()=>{
for await (const response of helpfulName()) {
...
})()

with the expected log output something like

at wrapper wrapper.ts(line)
at wrapper.next (<anonymous>)
at helpfulName helpfulName.ts(line)
at index.ts(line)

but instead helpfulName is missing

at wrapper wrapper.ts(line)
at wrapper.next (<anonymous>)
at index.ts(line)

I have tried various iterations of ES6/ES5 functions and different methods of exporting and wrapping in more functions, but I have been unable to get any reference to the helpfulName.ts from an error in wrapper(). Is this possible? Why is it not in the stack trace?

Jareth
  • 123
  • 1
  • 9
  • 1
    My guess is: A generator function returns a generator object. `helpfulName` returns that generator object. When the generator's `next` method is called, `helpfulName` is not involved anymore. That's the same with any other object. If I have a function that returns an object, e.g. `function foo() { return {bar() {}}`, calling the `bar` method later happens "outside" of the `foo` function, so `foo` won't appear in the stack. – Felix Kling Aug 11 '22 at 20:20

0 Answers0