error.cause needs to be logged manually to App Insights

Published on in JavaScript

If you are logging errors to Azure App Insights, and an Error object has a cause property (which too could be an Error object), the cause Error's message and stack properties are not shown in Azure App Insights. But you can log them manually.

Table of contents

Problem

  1. Use App Insights SDK for Node.js.

  2. Use the trackException method to log an error with a cause property:

    import * as appInsights from 'applicationinsights'
    
    try {
      throw new Error('foo')
    } catch (error) {
      appInsights.defaultClient.trackException({
        exception: new Error('bar', { cause: error }),
      })
    }
    

Expected behavior: both Error's message and stack trace are shown in App Insights.

Actual behavior: only the second Error's message (= 'bar') and stack trace are shown in App Insights.

A less contrived example

router.get('/foo', async (req, res) => {
  try {
    const data = await database.getFoo() // This can throw
    res.json(data)
  } catch (error) {
    appInsights.defaultClient.trackException({
      exception: new Error('GET /foo failed', { cause: error }),
    })
  }
})

Solution

Log the first/original Error's stack property manually:

try {
  // ...
} catch (error) {
  appInsights.defaultClient.trackException({
    exception: new Error('...'),
    properties:
      error instanceof Error ? { causeStack: error.stack } : undefined,
  })
}

Now the first/original Error's message and stack trace will be shown in App Insights under the "Custom Properties" heading.

Notes

  • The error instanceof Error check is needed because:

    The value of cause can be of any type. You should not make assumptions that the error you caught has an Error as its cause, in the same way that you cannot be sure the variable bound in the catch statement is an Error either.

    Source: Error: cause on MDN

  • No need to include error.message in the properties object, because in Node.js, error.stack also includes the error message.