Skip to content

feat(observability): fan-out errors Sentry + PostHog + opt-in flags#3489

Merged
PierreBrisorgueil merged 3 commits intomasterfrom
feat/observability-fanout-3486
Apr 23, 2026
Merged

feat(observability): fan-out errors Sentry + PostHog + opt-in flags#3489
PierreBrisorgueil merged 3 commits intomasterfrom
feat/observability-fanout-3486

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

Summary

  • New lib/services/errorTracker.js: captureException(err, ctx) fans out to Sentry (if dsn configured) AND PostHog (if apiKey + errorTracking===true). Silent no-op when neither is configured.
  • analytics.js: new captureException(err, ctx) method — sends PostHog $exception event with message, type, stack, requestId.
  • express.js: analyticsMiddleware now opt-in via posthog.autoCapture===true (was always-on). sentry.setupExpressErrorHandler replaced by errorTracker.setupExpressErrorHandler (includes fan-out middleware with userId/requestId context).
  • Config defaults: explicit posthog.errorTracking: false and posthog.autoCapture: false opt-in flags — default-safe invariant.
  • 11 unit tests covering all 4 tracker combinations + default-safe invariant.

Default-safe invariant

With only posthog.apiKey set: zero new features activate. All flags default to false.

Test plan

…3486)

- New `lib/services/errorTracker.js`: `captureException(err, ctx)` fans out to
  Sentry (if dsn) and PostHog (if apiKey + errorTracking===true). Silent no-op
  when neither is configured. `setupExpressErrorHandler` replaces the previous
  Sentry-only wiring in express.js.
- `analytics.js`: add `captureException(err, ctx)` — sends PostHog `$exception`
  event with message, type, stack, requestId.
- `express.js`: gate `analyticsMiddleware` behind `posthog.autoCapture===true`
  (was unconditionally mounted); replace `sentry.setupExpressErrorHandler` with
  `errorTracker.setupExpressErrorHandler` (Sentry handler + fan-out middleware).
- Config defaults: add `posthog.errorTracking: false` and `posthog.autoCapture:
  false` explicit opt-in flags — default-safe invariant.
- Tests: 11 unit tests covering all 4 tracker combinations + init + Express
  middleware, including default-safe invariant verification.

Closes #3486
Copilot AI review requested due to automatic review settings April 23, 2026 07:32
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 23, 2026

Warning

Rate limit exceeded

@PierreBrisorgueil has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 38 minutes and 25 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 38 minutes and 25 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 44c4896f-36ec-4549-a494-865c5ef37b6a

📥 Commits

Reviewing files that changed from the base of the PR and between f8542e3 and 9875abf.

📒 Files selected for processing (6)
  • config/defaults/development.config.js
  • lib/services/analytics.js
  • lib/services/errorTracker.js
  • lib/services/express.js
  • lib/services/tests/analytics.service.unit.tests.js
  • lib/services/tests/errorTracker.unit.tests.js
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/observability-fanout-3486

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 23, 2026

Codecov Report

❌ Patch coverage is 96.77419% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 85.95%. Comparing base (f4ba797) to head (9875abf).
⚠️ Report is 8 commits behind head on master.

Files with missing lines Patch % Lines
lib/services/express.js 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3489      +/-   ##
==========================================
+ Coverage   85.85%   85.95%   +0.10%     
==========================================
  Files         115      116       +1     
  Lines        2919     2948      +29     
  Branches      809      826      +17     
==========================================
+ Hits         2506     2534      +28     
- Misses        327      328       +1     
  Partials       86       86              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds an error-tracking “fan-out” layer so runtime exceptions can be reported to Sentry and/or PostHog, while making PostHog behaviors explicitly opt-in via config flags (default-safe when only posthog.apiKey is set).

Changes:

  • Introduces lib/services/errorTracker.js to fan-out captureException() to Sentry and PostHog (gated by config) and to mount an Express error handler.
  • Adds captureException() support to lib/services/analytics.js (PostHog $exception events).
  • Makes PostHog auto-capture middleware opt-in via posthog.autoCapture === true, and adds dev defaults for posthog.errorTracking / posthog.autoCapture.
  • Adds unit tests covering tracker combinations and the default-safe invariant.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
lib/services/tests/errorTracker.unit.tests.js Adds unit tests for errorTracker fan-out and Express error-handler wiring.
lib/services/express.js Gates PostHog auto-capture middleware behind an opt-in flag; switches to errorTracker error handler.
lib/services/errorTracker.js New service that fans out exception capture to Sentry and PostHog and mounts Express error middleware.
lib/services/analytics.js Adds PostHog $exception capture support.
config/defaults/development.config.js Adds explicit opt-in defaults for PostHog error tracking and auto-capture.

Comment thread lib/services/errorTracker.js Outdated
Comment thread lib/services/errorTracker.js Outdated
Comment thread lib/services/errorTracker.js Outdated
Comment thread lib/services/tests/errorTracker.unit.tests.js Outdated
Add 4 tests covering captureException: correct $exception event payload,
anonymous fallback distinctId, no-op when client not initialised, and
silent error swallowing. Ensures codecov/patch threshold is met.
…s rename, req.user._id

- `errorTracker.js`: add `captureExceptionPostHogOnly` to avoid double-reporting
  to Sentry in the Express error middleware (Sentry already captured via its own
  handler). Rename unused `res` to `_res`. Derive `distinctId` from
  `req.user._id` / `req.user.id` (not the non-existent `req.userId`).
- Tests: update setupExpressErrorHandler test to verify Sentry is NOT called
  from middleware. Add 2 new tests for req.user.id fallback and anonymous.
Copy link
Copy Markdown

@codacy-production codacy-production Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

The pull request is currently in a state that prevents a meaningful review because the provided code diff is empty. No files were included in the submission, which makes it impossible to verify the implementation of the lib/services/errorTracker.js service, the updates to analytics.js, or the Express middleware gating logic.

While the intent describes a robust 'default-safe' observability architecture, none of the seven core acceptance criteria can be confirmed. Additionally, the 11 unit tests mentioned in the PR description are not present in the diff. This missing implementation is a critical blocker that must be resolved before the PR can proceed.

About this PR

  • The provided code diff is empty. It is currently impossible to verify the implementation of the error tracking service, the logic for configuration-gated fan-outs to Sentry and PostHog, or the presence of the unit tests mentioned in the description. Please ensure the changes are correctly pushed and included in the PR.

Test suggestions

  • Error is sent to Sentry when DSN is configured
  • Error is sent to PostHog only when apiKey is present and errorTracking flag is true
  • Error tracking results in a silent no-op when no configurations are provided
  • PostHog analytics middleware is bypassed when autoCapture flag is false
  • CaptureException in analytics.js correctly formats message, type, stack, and requestId for PostHog
  • Verify 'default-safe' invariant: flags default to false when only the apiKey is provided
Prompt proposal for missing tests
Consider implementing these tests if applicable:
1. Error is sent to Sentry when DSN is configured
2. Error is sent to PostHog only when apiKey is present and errorTracking flag is true
3. Error tracking results in a silent no-op when no configurations are provided
4. PostHog analytics middleware is bypassed when autoCapture flag is false
5. CaptureException in analytics.js correctly formats message, type, stack, and requestId for PostHog
6. Verify 'default-safe' invariant: flags default to false when only the apiKey is provided

🗒️ Improve review quality by adding custom instructions

@codacy-production
Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

AI Reviewer: first review requested successfully. AI can make mistakes. Always validate suggestions.

Run reviewer

TIP This summary will be updated as you push new changes. Give us feedback

@PierreBrisorgueil PierreBrisorgueil merged commit ef1f6de into master Apr 23, 2026
6 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the feat/observability-fanout-3486 branch April 23, 2026 11:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(observability): fan-out errors Sentry + PostHog avec flags opt-in

2 participants