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
-
Use the
trackExceptionmethod to log an error with acauseproperty: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 Errorcheck is needed because:The value of
causecan be of any type. You should not make assumptions that the error you caught has anErroras itscause, in the same way that you cannot be sure the variable bound in thecatchstatement is anErroreither.Source: Error: cause on MDN
-
No need to include
error.messagein thepropertiesobject, because in Node.js,error.stackalso includes the error message.