Skip to content

Commit 7185a53

Browse files
authored
feat(react): Add Sentry.reactErrorHandler (#12147)
This PR introduces `Sentry.reactErrorHandler`, which looks like so: ```js import * as Sentry from '@sentry/react'; import { hydrateRoot } from "react-dom/client"; ReactDOM.hydrateRoot( document.getElementById("root"), <React.StrictMode> <App /> </React.StrictMode>, { onUncaughtError: Sentry.reactErrorHandler(), onCaughtError: Sentry.reactErrorHandler((error, errorInfo) => { // optional callback if users want custom config. }), } ); ``` To validate this change, we add a react 19 e2e test.
1 parent 4644dd7 commit 7185a53

21 files changed

+540
-149
lines changed

.github/workflows/build.yml

+1
Original file line numberDiff line numberDiff line change
@@ -1009,6 +1009,7 @@ jobs:
10091009
'nextjs-app-dir',
10101010
'nextjs-14',
10111011
'nextjs-15',
1012+
'react-19',
10121013
'react-create-hash-router',
10131014
'react-router-6-use-routes',
10141015
'react-router-5',
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# production
12+
/build
13+
14+
# misc
15+
.DS_Store
16+
.env.local
17+
.env.development.local
18+
.env.test.local
19+
.env.production.local
20+
21+
npm-debug.log*
22+
yarn-debug.log*
23+
yarn-error.log*
24+
25+
/test-results/
26+
/playwright-report/
27+
/playwright/.cache/
28+
29+
!*.d.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
@sentry:registry=http://127.0.0.1:4873
2+
@sentry-internal:registry=http://127.0.0.1:4873
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
{
2+
"name": "react-19-test-app",
3+
"version": "0.1.0",
4+
"private": true,
5+
"dependencies": {
6+
"@sentry/react": "latest || *",
7+
"@testing-library/jest-dom": "5.14.1",
8+
"@testing-library/react": "13.0.0",
9+
"@testing-library/user-event": "13.2.1",
10+
"history": "4.9.0",
11+
"@types/history": "4.7.11",
12+
"@types/jest": "27.0.1",
13+
"@types/node": "16.7.13",
14+
"@types/react": "npm:types-react@rc",
15+
"@types/react-dom": "npm:types-react-dom@rc",
16+
"react": "19.0.0-rc-935180c7e0-20240524",
17+
"react-dom": "19.0.0-rc-935180c7e0-20240524",
18+
"react-scripts": "5.0.1",
19+
"typescript": "4.9.5",
20+
"web-vitals": "2.1.0"
21+
},
22+
"scripts": {
23+
"build": "react-scripts build",
24+
"dev": "react-scripts start",
25+
"start": "serve -s build",
26+
"test": "playwright test",
27+
"clean": "npx rimraf node_modules pnpm-lock.yaml",
28+
"test:build": "pnpm install && npx playwright install && pnpm build",
29+
"test:assert": "pnpm test"
30+
},
31+
"eslintConfig": {
32+
"extends": [
33+
"react-app",
34+
"react-app/jest"
35+
]
36+
},
37+
"browserslist": {
38+
"production": [
39+
">0.2%",
40+
"not dead",
41+
"not op_mini all"
42+
],
43+
"development": [
44+
"last 1 chrome version",
45+
"last 1 firefox version",
46+
"last 1 safari version"
47+
]
48+
},
49+
"devDependencies": {
50+
"@playwright/test": "^1.43.1",
51+
"@sentry-internal/event-proxy-server": "link:../../../event-proxy-server",
52+
"serve": "14.0.1"
53+
},
54+
"volta": {
55+
"extends": "../../package.json"
56+
}
57+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import type { PlaywrightTestConfig } from '@playwright/test';
2+
import { devices } from '@playwright/test';
3+
4+
const reactPort = 3030;
5+
const eventProxyPort = 3031;
6+
7+
/**
8+
* See https://playwright.dev/docs/test-configuration.
9+
*/
10+
const config: PlaywrightTestConfig = {
11+
testDir: './tests',
12+
/* Maximum time one test can run for. */
13+
timeout: 150_000,
14+
expect: {
15+
/**
16+
* Maximum time expect() should wait for the condition to be met.
17+
* For example in `await expect(locator).toHaveText();`
18+
*/
19+
timeout: 5000,
20+
},
21+
/* Run tests in files in parallel */
22+
fullyParallel: true,
23+
/* Fail the build on CI if you accidentally left test.only in the source code. */
24+
forbidOnly: !!process.env.CI,
25+
/* Retry on CI only */
26+
retries: 0,
27+
/* Opt out of parallel tests on CI. */
28+
workers: 1,
29+
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
30+
reporter: 'list',
31+
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
32+
use: {
33+
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
34+
actionTimeout: 0,
35+
36+
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
37+
trace: 'on-first-retry',
38+
39+
baseURL: `http://localhost:${reactPort}`,
40+
},
41+
42+
/* Configure projects for major browsers */
43+
projects: [
44+
{
45+
name: 'chromium',
46+
use: {
47+
...devices['Desktop Chrome'],
48+
},
49+
},
50+
// For now we only test Chrome!
51+
// {
52+
// name: 'firefox',
53+
// use: {
54+
// ...devices['Desktop Firefox'],
55+
// },
56+
// },
57+
// {
58+
// name: 'webkit',
59+
// use: {
60+
// ...devices['Desktop Safari'],
61+
// },
62+
// },
63+
],
64+
65+
/* Run your local dev server before starting the tests */
66+
67+
webServer: [
68+
{
69+
command: 'node start-event-proxy.mjs',
70+
port: eventProxyPort,
71+
},
72+
{
73+
command: 'pnpm start',
74+
port: reactPort,
75+
env: {
76+
PORT: `${reactPort}`,
77+
},
78+
},
79+
],
80+
};
81+
82+
export default config;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1" />
6+
<meta name="theme-color" content="#000000" />
7+
<meta name="description" content="Web site created using create-react-app" />
8+
<title>React App</title>
9+
</head>
10+
<body>
11+
<noscript>You need to enable JavaScript to run this app.</noscript>
12+
<div id="root"></div>
13+
<!--
14+
This HTML file is a template.
15+
If you open it directly in the browser, you will see an empty page.
16+
17+
You can add webfonts, meta tags, or analytics to this file.
18+
The build step will place the bundled scripts into the <body> tag.
19+
20+
To begin the development, run `npm start` or `yarn start`.
21+
To create a production bundle, use `npm run build` or `yarn build`.
22+
-->
23+
</body>
24+
</html>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
interface Window {
2+
recordedTransactions?: string[];
3+
capturedExceptionId?: string;
4+
sentryReplayId?: string;
5+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import * as Sentry from '@sentry/react';
2+
// biome-ignore lint/nursery/noUnusedImports: <explanation>
3+
import React from 'react';
4+
import ReactDOM from 'react-dom/client';
5+
import Index from './pages/Index';
6+
7+
Sentry.init({
8+
environment: 'qa', // dynamic sampling bias to keep transactions
9+
dsn:
10+
process.env.REACT_APP_E2E_TEST_DSN ||
11+
'https://3b6c388182fb435097f41d181be2b2ba@o4504321058471936.ingest.sentry.io/4504321066008576',
12+
release: 'e2e-test',
13+
tunnel: 'http://localhost:3031/', // proxy server
14+
});
15+
16+
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement, {
17+
onUncaughtError: Sentry.reactErrorHandler((error, errorInfo) => {
18+
console.warn(error, errorInfo);
19+
}),
20+
onCaughtError: Sentry.reactErrorHandler((error, errorInfo) => {
21+
console.warn(error, errorInfo);
22+
}),
23+
});
24+
25+
root.render(
26+
<div>
27+
<Index />
28+
</div>,
29+
);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import * as React from 'react';
2+
3+
const Index = () => {
4+
const [caughtError, setCaughtError] = React.useState(false);
5+
const [uncaughtError, setUncaughtError] = React.useState(false);
6+
7+
return (
8+
<>
9+
<div>
10+
<SampleErrorBoundary>
11+
<h1>React 19</h1>
12+
{caughtError && <Throw error="caught" />}
13+
<button id="caughtError-button" onClick={() => setCaughtError(true)}>
14+
Throw caught error
15+
</button>
16+
</SampleErrorBoundary>
17+
</div>
18+
<div>
19+
{uncaughtError && <Throw error="uncaught" />}
20+
<button id="uncaughtError-button" onClick={() => setUncaughtError(true)}>
21+
Throw uncaught error
22+
</button>
23+
</div>
24+
</>
25+
);
26+
};
27+
28+
function Throw({ error }) {
29+
throw new Error(`${error} error`);
30+
}
31+
32+
class SampleErrorBoundary extends React.Component {
33+
constructor(props) {
34+
super(props);
35+
this.state = { error: null };
36+
}
37+
38+
componentDidCatch(error, errorInfo) {
39+
this.setState({ error });
40+
// no-op
41+
}
42+
43+
render() {
44+
if (this.state.error) {
45+
return <div>Caught an error: {JSON.stringify(this.state.error)}</div>;
46+
}
47+
return this.props.children;
48+
}
49+
}
50+
51+
export default Index;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/// <reference types="react-scripts" />
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { startEventProxyServer } from '@sentry-internal/event-proxy-server';
2+
3+
startEventProxyServer({
4+
port: 3031,
5+
proxyServerName: 'react-19',
6+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { expect, test } from '@playwright/test';
2+
import { waitForError } from '@sentry-internal/event-proxy-server';
3+
4+
test('Catches errors caught by error boundary', async ({ page }) => {
5+
page.on('console', message => {
6+
expect(message.text()).toContain('caught error');
7+
});
8+
9+
const errorEventPromise = waitForError('react-19', event => {
10+
return !event.type && event.exception?.values?.[0]?.value === 'caught error';
11+
});
12+
13+
await page.goto('/');
14+
15+
const exceptionButton = page.locator('id=caughtError-button');
16+
await exceptionButton.click();
17+
18+
const errorEvent = await errorEventPromise;
19+
20+
expect(errorEvent.exception?.values).toHaveLength(2);
21+
expect(errorEvent.exception?.values?.[0]?.value).toBe('caught error');
22+
});
23+
24+
test('Catches errors uncaught by error boundary', async ({ page }) => {
25+
page.on('console', message => {
26+
expect(message.text()).toContain('uncaught error');
27+
});
28+
29+
const errorEventPromise = waitForError('react-19', event => {
30+
return !event.type && event.exception?.values?.[0]?.value === 'uncaught error';
31+
});
32+
33+
await page.goto('/');
34+
35+
const exceptionButton = page.locator('id=uncaughtError-button');
36+
await exceptionButton.click();
37+
38+
const errorEvent = await errorEventPromise;
39+
40+
expect(errorEvent.exception?.values).toHaveLength(2);
41+
expect(errorEvent.exception?.values?.[0]?.value).toBe('uncaught error');
42+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"compilerOptions": {
3+
"target": "es2018",
4+
"lib": ["dom", "dom.iterable", "esnext"],
5+
"allowJs": true,
6+
"skipLibCheck": true,
7+
"esModuleInterop": true,
8+
"allowSyntheticDefaultImports": true,
9+
"strict": true,
10+
"forceConsistentCasingInFileNames": true,
11+
"noFallthroughCasesInSwitch": true,
12+
"module": "esnext",
13+
"moduleResolution": "node",
14+
"resolveJsonModule": true,
15+
"isolatedModules": true,
16+
"noEmit": true,
17+
"jsx": "react"
18+
},
19+
"include": ["src", "tests"]
20+
}

0 commit comments

Comments
 (0)