microsoft / ApplicationInsights-node.js

Microsoft Application Insights SDK for Node.js
MIT License
320 stars 138 forks source link

"Cannot read property 'operation' of null" when trying to use correlationContext.operation.parentId #815

Closed f0o closed 2 years ago

f0o commented 2 years ago

When using the Example from the README.md it instantly fails;

Removing setAutoDependencyCorrelation(false) from the setup-line will work but README.md strongly notes that it should be disabled:

Because of the way JavaScript handles callbacks, additional work is necessary to track a request across external dependencies and later callbacks. By default this additional tracking is enabled; disable it by calling setAutoDependencyCorrelation(false) as described in the Configuration section below.

So what's the right way of doing this then? README.md seems to show a defunc codepath

Full Code:

const appInsights = require("applicationinsights");
appInsights.setup().setAutoDependencyCorrelation(false).start();

async function handler (context, req) {
  return context.res.body = "Hello World"
}
module.exports = async function (context, req) {
    const correlationContext = appInsights.startOperation(context, req);
    return appInsights.wrapWithCorrelationContext(async () => {
        const startTime = Date.now(); // Start trackRequest timer

        // Run the Function
        await handler(context, req);

        // Track Request on completion
        appInsights.defaultClient.trackRequest({
                name: context.req.method + " " + context.req.url,
                resultCode: context.res.status,
                success: true,
                url: req.url,
                duration: Date.now() - startTime,
                id: correlationContext.operation.parentId,
        });
        appInsights.defaultClient.flush();
    }, correlationContext)();
}

Error:

Exception: TypeError: Cannot read property 'operation' of null
Stack: TypeError: Cannot read property 'operation' of null
f0o commented 2 years ago

After running it by some others I guess the quoted part was not meant to be any form of recommendation and merely an "FYI"... it was a bit misleading to me