Skip to content

Extract diagnostic info from Safari CustomEvent rejections - #8173

Merged
mattgodbolt merged 3 commits into
mainfrom
claude/fix-sentry-COMPILER-EXPLORER-DXM
Oct 7, 2025
Merged

mattgodbolt merged 3 commits into
mainfrom
claude/fix-sentry-COMPILER-EXPLORER-DXM

Conversation

@mattgodbolt

Copy link
Copy Markdown
Member

Fixes #8172
Fixes COMPILER-EXPLORER-DXM

Problem

Sentry issue COMPILER-EXPLORER-DXM has accumulated 7,018+ occurrences with essentially no diagnostic information:

  • Error: CustomEvent: Event 'CustomEvent' (type=unhandledrejection) captured as promise rejection
  • No stacktrace
  • Safari-specific (Safari 26.0 on macOS)
  • No actionable information to debug the issue

Root Cause

Safari sometimes rejects promises with CustomEvent/Event objects instead of Error objects. Our unhandledrejection handler in static/sentry.ts:110-122 converts non-Error rejections to Error objects using:

const errorMessage = typeof reason === 'string' ? reason 
    : `Non-Error rejection: ${JSON.stringify(reason)}`;

When JSON.stringify() is called on Event objects, it returns {} because Event properties are non-enumerable. This loses all valuable diagnostic information like:

  • event.type - the event type
  • event.target - what triggered the event
  • event.detail - custom data for CustomEvents

Evidence

Solution

Extract meaningful properties from Event/CustomEvent objects before stringifying:

  1. Add type guard: isEventLike() to detect Event/CustomEvent objects
  2. Extract properties: formatEventRejection() to get type, target, detail
  3. Cleaner code: Refactor with ternary chain and modern TypeScript patterns
  4. Better diagnostics: Use Object.assign() for type-safe property addition

Before

Non-Error rejection: {}

After

Event rejection: type="unhandledrejection", target="Window", detail={...}

Impact

This will allow us to:

  1. ✅ Identify the actual source of these Safari rejections
  2. ✅ Determine if they're from CE code, third-party libraries, or browser extensions
  3. ✅ Decide if they need fixing or should be filtered out
  4. ✅ Get actionable diagnostic information instead of empty objects

Test Plan

  • ✅ TypeScript type checking passes
  • ✅ Linter passes with auto-formatting
  • ✅ Related tests pass
  • ✅ Pre-commit hooks pass
  • Manual testing: Wait for Safari users to trigger these errors and verify we now get useful diagnostic info in Sentry

Code Review Notes

The fix operates at the right layer - transforming Events into meaningful Error messages at the point of rejection, before Sentry sees them. This is different from Sentry's ExtraErrorData integration which operates on already-serialized errors.

🤖 Generated with Claude Code

Fixes #8172
Fixes COMPILER-EXPLORER-DXM

Safari sometimes rejects promises with CustomEvent/Event objects instead
of Error objects. When JSON.stringify() is called on these Event objects,
it returns '{}' because Event properties are non-enumerable.

This fix extracts useful diagnostic properties (type, target, detail)
from Event/CustomEvent objects before creating the error message,
providing actionable information instead of empty objects.

Changes:
- Add isEventLike() type guard to detect Event/CustomEvent objects
- Add formatEventRejection() to extract meaningful Event properties
- Refactor unhandledrejection handler with cleaner ternary chain
- Use Object.assign() for type-safe property addition
- Add references to GitHub issue and related Sentry SDK issue

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@github-actions github-actions Bot added the ui label Oct 7, 2025
@mattgodbolt
mattgodbolt requested a review from Copilot October 7, 2025 20:17

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

Improves Safari-specific error handling by extracting meaningful diagnostic information from CustomEvent/Event objects that are rejected as promises, replacing empty object serialization with descriptive error messages.

  • Enhanced unhandled rejection handler to detect and format Event/CustomEvent objects
  • Added type guards and formatting functions for better error diagnostics
  • Refactored error construction using modern TypeScript patterns

Comment thread static/sentry.ts
}

function isEventLike(value: unknown): value is Event {
return value instanceof Event || value?.constructor?.name === 'Event' || value?.constructor?.name === 'CustomEvent';

Copilot AI Oct 7, 2025

Copy link

Choose a reason for hiding this comment

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

The constructor name check could be bypassed by objects with spoofed constructor names. Consider adding additional property checks like 'type' in value && 'target' in value to verify Event-like structure more reliably.

Suggested change
return value instanceof Event || value?.constructor?.name === 'Event' || value?.constructor?.name === 'CustomEvent';
return (
value instanceof Event ||
(typeof value === 'object' &&
value !== null &&
'type' in value &&
'target' in value)
);

Copilot uses AI. Check for mistakes.
Comment thread static/sentry.ts Outdated
let message = `Event rejection: type="${evt.type}", target="${targetName}"`;

if ('detail' in evt && evt.detail !== undefined) {
message += `, detail=${JSON.stringify(evt.detail)}`;

Copilot AI Oct 7, 2025

Copy link

Choose a reason for hiding this comment

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

JSON.stringify on evt.detail could throw if the detail contains circular references or non-serializable values. Consider wrapping in a try-catch or using a safer serialization method.

Suggested change
message += `, detail=${JSON.stringify(evt.detail)}`;
let detailStr: string;
try {
detailStr = JSON.stringify(evt.detail);
} catch (err) {
detailStr = '[Unserializable detail]';
}
message += `, detail=${detailStr}`;

Copilot uses AI. Check for mistakes.
Comment thread static/sentry.ts

// Preserve original reason for debugging
(reason as any).originalReason = event.reason;
reason = Object.assign(new Error(errorMessage), {originalReason: event.reason});

Copilot AI Oct 7, 2025

Copy link

Choose a reason for hiding this comment

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

[nitpick] Using Object.assign to add properties to Error objects can be less clear than explicit property assignment. Consider using (reason as any).originalReason = event.reason for better readability and consistency with the removed code pattern.

Suggested change
reason = Object.assign(new Error(errorMessage), {originalReason: event.reason});
reason = new Error(errorMessage);
(reason as any).originalReason = event.reason;

Copilot uses AI. Check for mistakes.
@mattgodbolt

Copy link
Copy Markdown
Member Author

Thanks for the review, @copilot! Let me address each suggestion:

✅ Suggestion #2: Protect JSON.stringify() from throwing (ACCEPTED)

Great catch! I've updated the code to wrap JSON.stringify(evt.detail) in a try-catch block. Since we're in an error handler, the last thing we want is for the error handler itself to throw on circular references, BigInts, or other non-serializable values.

try {
    message += `, detail=${JSON.stringify(evt.detail)}`;
} catch {
    message += ', detail=[Unserializable]';
}

This is good defensive programming practice.


❌ Suggestion #1: Property-based duck typing (DECLINED)

I appreciate the security concern, but I'm keeping the constructor-based approach for this specific use case:

Why constructor checks are better here:

  • More precise: We're specifically looking for browser-generated Event objects from Safari
  • Fewer false positives: Property-based duck typing ('type' in value && 'target' in value) would match any object with those properties, like {type: "foo", target: "bar"}
  • Safari context: These are real Event objects rejected by Safari's promise mechanism, not user code

If an object has spoofed its constructor name to be "Event" or "CustomEvent", it's trying very hard to look like an Event, and treating it as one in this error-reporting context is reasonable.

The instanceof Event check handles the normal case, while the constructor name checks handle cross-realm scenarios where instanceof might fail.


❌ Suggestion #3: Use explicit assignment instead of Object.assign() (DECLINED)

I'm keeping the Object.assign() approach because it's the more modern TypeScript pattern:

Benefits of the current approach:

  • Single expression (functional style)
  • Type-safe property addition
  • Modern TypeScript idiom recommended by our TS code review
  • More concise without sacrificing clarity

Comparison:

// Our approach (modern, functional)
reason = Object.assign(new Error(errorMessage), {originalReason: event.reason});

// Alternative (imperative, two statements, still needs type assertion)
reason = new Error(errorMessage);
(reason as any).originalReason = event.reason;

The Object.assign() pattern is well-established in modern TypeScript and is actually clearer than the multi-statement alternative.


Updated the code with the JSON.stringify protection. Thanks for the thorough review!

mattgodbolt and others added 2 commits October 7, 2025 15:34
Addresses Copilot review feedback: Wrap JSON.stringify(evt.detail) in
try-catch to prevent the error handler from throwing on circular
references, BigInts, or other non-serializable values.

Uses '[Unserializable]' fallback if stringification fails.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@mattgodbolt
mattgodbolt merged commit 5ca970e into main Oct 7, 2025
@mattgodbolt
mattgodbolt deleted the claude/fix-sentry-COMPILER-EXPLORER-DXM branch October 7, 2025 20:44
@partouf partouf added the live This is now live label Oct 13, 2025
@partouf

partouf commented Oct 13, 2025

Copy link
Copy Markdown
Member

This is now live

@sentry

sentry Bot commented Oct 16, 2025 •

Copy link
Copy Markdown

Issues attributed to commits in this pull request

This pull request was merged and Sentry observed the following issues:

OfekShilon added a commit that referenced this pull request Nov 21, 2026
Fixes Sentry
[COMPILER-EXPLORER-EHY](https://compiler-explorer.sentry.io/issues/COMPILER-EXPLORER-EHY)
("Error: Non-Error rejection: {}", 351 events in 30 days) and its
sibling
[COMPILER-EXPLORER-EJ9](https://compiler-explorer.sentry.io/issues/COMPILER-EXPLORER-EJ9)
("Non-Error rejection: undefined", 5.8k events in total).

## Root cause
`SetupSentry()` adds its own `unhandledrejection` listener, but Sentry's
default `GlobalHandlers` integration already captures every unhandled
rejection (`onunhandledrejection: true`; we don't override
`integrations`). That means every rejection gets reported twice:

- **Sentry's built-in copy** handles cross-realm Errors properly via
`isError`, and turns Event/CustomEvent rejections into `Event
'CustomEvent' (type=…) captured as promise rejection`. It also puts the
type, target and detail into `extra.__serialized__`.
- **CE's copy** checks `reason instanceof Error`, and that check fails
for Errors created in another realm, such as Safari extension content
scripts. It then runs `JSON.stringify(reason)` on them, and since Error
properties are non-enumerable the result is `{}`.

Evidence from Sentry:
- EHY's events line up timestamp for timestamp with properly titled
built-in events in other issues. One example is
[COMPILER-EXPLORER-DJ2](https://compiler-explorer.sentry.io/issues/COMPILER-EXPLORER-DJ2):
`Invalid call to runtime.sendMessage(). Tab not found.` from a Safari
extension, with mechanism
`auto.browser.global_handlers.onunhandledrejection`.
- The "Request timeout …" variants of EHY match their built-in twins
count for count.
- The title of the issue #8173 set out to fix (DXM, `Event 'CustomEvent'
(type=unhandledrejection) captured as promise rejection`) is itself the
built-in handler's format. So the built-in handler was already reporting
those events.

## Fix
Remove the custom listener, together with the `isEventLike` and
`formatEventRejection` helpers that only it used. After this, each
rejection is reported once, by Sentry's handler, which gives the more
informative result in every case:

| rejection reason | built-in handler | removed handler |
|---|---|---|
| cross-realm `Error` | real type + message + stack | `Non-Error
rejection: {}` |
| `undefined` / primitive | `Non-Error promise rejection captured with
value: undefined` | `Non-Error rejection: undefined` (no stack) |
| `CustomEvent` | `Event 'CustomEvent' (type=…)` + serialized
type/target/detail | `Event rejection: type=…` |

Once this ships, the EHY and EJ9 groups will stop receiving events. The
real underlying errors (DJ2 and similar) keep their own issues, where
they can be triaged or ignored on their merits.

## Test plan
- [x] `npm run ts-check`, `npm run lint`, `npm run test-min`
- [ ] After deploy: EHY and EJ9 stop receiving events, and the built-in
twins (e.g. DJ2) keep reporting at their usual rate.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

live This is now live ui

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Safari CustomEvent promise rejections create uninformative Sentry reports (COMPILER-EXPLORER-DXM)

3 participants