patternjavascriptModerate
Sentry error tracking: capturing exceptions with full context in Node.js
Viewed 0 times
@sentry/node ^8.x
Sentryerror trackingcaptureExceptionbeforeSendbreadcrumbsDSNrelease trackingPII scrubbing
nodejs
Problem
Errors in production are discovered through user complaints rather than automated detection. Stack traces in logs lack the context needed to reproduce the issue: what user triggered it, what they were doing, and what the application state was.
Solution
Integrate Sentry to automatically capture unhandled exceptions and provide rich context for each error.
const Sentry = require('@sentry/node');
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV,
release: process.env.APP_VERSION,
tracesSampleRate: 0.1, // 10% of transactions
beforeSend(event) {
// Scrub PII from events before sending
if (event.user) delete event.user.email;
return event;
},
});
// Set user context for better error attribution
Sentry.setUser({ id: req.user.id });
// Add breadcrumbs for custom events leading up to an error
Sentry.addBreadcrumb({
category: 'payment',
message: 'Initiating payment for order ' + orderId,
level: 'info',
});
// Manually capture with extra context
try {
await processPayment(order);
} catch (err) {
Sentry.captureException(err, {
tags: { orderId: order.id },
extra: { paymentProvider: order.provider },
});
throw err;
}Why
Sentry groups errors by stack trace fingerprint, showing occurrence count and affected users. This transforms error monitoring from log searching to a prioritized queue of distinct issues.
Gotchas
- Never send PII (emails, passwords, SSNs) to Sentry — use beforeSend to scrub sensitive data
- tracesSampleRate at 1.0 (100%) is expensive in high-traffic services — start at 0.01-0.1
- Sentry's auto-instrumentation captures errors thrown inside async functions if using the Node profiler, but not fire-and-forget promises — always handle rejection
- Use Sentry releases and commits integration so errors are attributed to specific deploys and code owners
Context
Adding automated error detection and reporting to a Node.js application
Revisions (0)
No revisions yet.