Skip to content

[React 19] Allow access of default error callbacks in onCaughtError and onUncaughtError #29581

@AbhiPrasad

Description

@AbhiPrasad

Hey React team! We at Sentry have been working on adding support for the new onCaughtError and onUncaughtError root options in React 19 for error reporting.

Here's a PR I'm iterating on atm: getsentry/sentry-javascript#12147

The API we are looking to add looks something like so:

import { reactErrorHandler } from '@sentry/react';
import { hydrateRoot } from "react-dom/client";

ReactDOM.hydrateRoot(
  document.getElementById("root") as HTMLElement,
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  {
    onUncaughtError: reactErrorHandler(),
    onCaughtError: reactErrorHandler((error, errorInfo) => {
      // optional callback if users want more/custom config in addition?
    }),
  }
);

The only issue with Sentry.reactErrorHandler in the current form is that setting the onUncaughtError or onCaughtError options overrides the defaults for onUncaughtError and onCaughtError, which means you lose out on the dev mode logging like so:

if (__DEV__) {
const componentStack =
errorInfo.componentStack != null ? errorInfo.componentStack : '';
const componentNameMessage = componentName
? `An error occurred in the <${componentName}> component:`
: 'An error occurred in one of your React components:';
console['warn'](
'%s\n%s\n\n%s',
componentNameMessage,
componentStack || '',
'Consider adding an error boundary to your tree to customize error handling behavior.\n' +
'Visit https://react.dev/link/error-boundaries to learn more about error boundaries.',
);
}

In this case there is no way for us to replicate the An error occurred in the <${componentName}> component: message (because componentName is private API), so asking users to add Sentry.reactErrorHandler degrades their local development experience.

This means if someone adds Sentry, or their own error logging via these hooks, they lose out on useful messaging in dev mode. We could recommend to users to make this production-only, but folks also use Sentry error reporting locally via Spotlight, Sentry for development.

Is there a way we can get access to the original onCaughtError or onUncaughtError handler so we can execute that, while sending the error to Sentry at the same time? Or is there are alternate way we can design this API to make that happen?

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions