Skip to content

Capture structured Error.cause data#148

Merged
petyosi merged 7 commits into
mainfrom
petyosi/structured-error-cause
Jun 18, 2026
Merged

Capture structured Error.cause data#148
petyosi merged 7 commits into
mainfrom
petyosi/structured-error-cause

Conversation

@petyosi

@petyosi petyosi commented Jun 18, 2026

Copy link
Copy Markdown
Member

Summary

  • include Error.cause chains in recorded exception stacktraces for reportError() and span/instrument callback failures
  • add a structured exception.cause Logfire attribute that uses the existing JSON serialization + logfire.json_schema metadata path
  • preserve useful enumerable cause metadata such as code, statusCode, details, operation, and nested causes
  • add an Express demo endpoint at /structured-cause-error so the resulting shape can be inspected in the Logfire UI

Context

A user reported that the JavaScript SDK currently omits Error.cause, which is often where the actionable debugging context lives. Upstream OpenTelemetry JS currently maps exceptions to exception.type, exception.message, and exception.stacktrace, so passing a raw JS Error to recordException() loses cause.

Relevant upstream context:

Approach

This keeps the standard OTel attributes useful by appending the cause chain to exception.stacktrace. That matches the upstream direction in open-telemetry/opentelemetry-js#6423 and is compatible with generic OTel consumers.

For Logfire specifically, we also emit exception.cause as a serialized JSON object using the SDK's existing object serialization mechanism. That gives the Logfire UI structured data with logfire.json_schema, instead of flattening all cause information into an opaque stack string. The structured object is recursive, handles circular chains, and includes enumerable custom fields on caused errors.

This avoids introducing a new dependency or waiting on OTel semantic-convention changes while still leaving the standard exception.* surface intact.

Validation

  • vp run logfire#test -- -t "cause chain"
  • vp run logfire#typecheck
  • vp run logfire#test
  • vp fmt --check packages/logfire-api/src/index.ts packages/logfire-api/src/index.test.ts .changeset/tame-errors-cause.md
  • pnpm build
  • pnpm --dir examples/express exec tsc --noEmit
  • local Express smoke test with LOGFIRE_SEND_TO_LOGFIRE=false against /structured-cause-error

@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds support for Error.cause chains in exception recording. New normalization utilities in packages/logfire-api/src/index.ts handle recursive cause-aware stack formatting, circular-cause detection, optional error code extraction, and normalization of cause payloads into an Exception shape. buildSerializedLogfireAttributes is refactored to return both raw and serialized attributes; recordSpanException is updated to accept these serialization attributes and serialize exception.cause onto the span when present. normalizeReportError is extended to include exception.cause in attributes and cause-inclusive stacktraces. Comprehensive tests cover the span and reportError paths with single, nested, and circular cause chains. The Express example gains a /structured-cause-error demo route with a renamed env variable (LOGFIRE_TOKEN) and package metadata updates.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately captures the main change: adding support for structured Error.cause data in exception handling.
Description check ✅ Passed The description comprehensively explains the feature, approach, context, and validation steps, directly aligned with the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch petyosi/structured-error-cause

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/logfire-api/src/index.test.ts (1)

589-650: ⚡ Quick win

Add explicit tests for nested and circular cause chains.

These tests currently validate only a single-level cause. Since this PR’s behavior includes recursive chains and circular-chain handling, please add at least one nested (2+ levels) and one circular-cause regression test in both span and reportError paths to lock the contract.

Also applies to: 743-792

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/logfire-api/src/index.test.ts` around lines 589 - 650, Add two new
test cases for the span function path and two for the reportError function path
to validate handling of complex cause chains. The first set should test nested
cause chains where an error has a cause that itself has a cause (2+ levels
deep), similar to the existing single-level cause test but with multiple levels
of error nesting. The second set should test circular cause chains where an
error's cause chain eventually references back to the original error or creates
a loop, ensuring the implementation handles these edge cases without infinite
recursion or stack overflow. Use the same structure as the existing test but
construct errors with nested properties and circular references in the cause
chain to verify both span and reportError paths properly record and serialize
these complex scenarios.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/logfire-api/src/index.test.ts`:
- Around line 589-650: Add two new test cases for the span function path and two
for the reportError function path to validate handling of complex cause chains.
The first set should test nested cause chains where an error has a cause that
itself has a cause (2+ levels deep), similar to the existing single-level cause
test but with multiple levels of error nesting. The second set should test
circular cause chains where an error's cause chain eventually references back to
the original error or creates a loop, ensuring the implementation handles these
edge cases without infinite recursion or stack overflow. Use the same structure
as the existing test but construct errors with nested properties and circular
references in the cause chain to verify both span and reportError paths properly
record and serialize these complex scenarios.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 38da35cf-6988-49f4-ba47-836f4e747ca7

📥 Commits

Reviewing files that changed from the base of the PR and between ce583e1 and da49c6f.

📒 Files selected for processing (5)
  • .changeset/tame-errors-cause.md
  • examples/express/.env.example
  • examples/express/app.ts
  • packages/logfire-api/src/index.test.ts
  • packages/logfire-api/src/index.ts

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 enhances the Logfire JS SDK’s exception reporting to preserve Error.cause chains by (a) appending the cause chain into the recorded exception stacktrace and (b) emitting a structured exception.cause attribute using the existing JSON serialization + logfire.json_schema metadata, with an accompanying Express demo endpoint.

Changes:

  • Extend exception recording to include Error.cause chains in stacktraces and add a structured exception.cause attribute (for reportError() and span/instrument callback failures).
  • Add tests covering the new structured-cause behavior for span() failures and reportError().
  • Update the Express example with a /structured-cause-error demo route and align the example env var name to LOGFIRE_TOKEN (plus a changeset for a patch release).

Reviewed changes

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

Show a summary per file
File Description
packages/logfire-api/src/index.ts Adds cause-chain stack formatting and structured exception.cause serialization for span/reportError exception paths.
packages/logfire-api/src/index.test.ts Adds unit tests asserting cause-chain stacktrace output and JSON-schema-backed structured exception.cause.
examples/express/app.ts Adds a demo error generator + /structured-cause-error route and attaches demo metadata to reportError().
examples/express/.env.example Updates the example token env var to LOGFIRE_TOKEN.
.changeset/tame-errors-cause.md Declares a patch changeset for the new structured cause behavior.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread examples/express/app.ts
Comment thread packages/logfire-api/src/index.test.ts
@petyosi
petyosi merged commit 22bd8ec into main Jun 18, 2026
3 checks passed
@petyosi
petyosi deleted the petyosi/structured-error-cause branch June 18, 2026 08:21
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.

2 participants