Skip to content

Commit 2fe2285

Browse files
authored
docs(react): Add error boundary docs for react-router (#11326)
1 parent 3cbe50f commit 2fe2285

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

docs/platforms/javascript/guides/react/features/react-router.mdx

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,57 @@ You can instrument [`createMemoryRouter`](https://reactrouter.com/en/main/router
8282

8383
</Alert>
8484

85+
### Custom Error Boundaries
86+
87+
When using `react-router`, errors thrown inside route elements will only be re-thrown in **development mode** while using [`strict mode`](https://react.dev/reference/react/StrictMode). In production, these errors won't be surfaced unless manually captured. If you **don't** have a custom error boundary in place, `react-router` will create a default one that "swallows" all errors.
88+
89+
<Note>
90+
Note, that this only applies to render method and lifecycle errors since React doesn't need error boundaries to handle errors in event handlers.
91+
</Note>
92+
93+
To send errors to Sentry while using a custom error boundary, use the `Sentry.captureException` method:
94+
95+
```jsx {11, 28}
96+
// router setup
97+
const sentryCreateBrowserRouter = wrapCreateBrowserRouter(createBrowserRouter);
98+
const router = sentryCreateBrowserRouter([
99+
{
100+
path: "/",
101+
element: <YourLayout />,
102+
children: [
103+
{
104+
path: "",
105+
element: <Outlet />,
106+
errorElement: <YourCustomRootErrorBoundary />,
107+
children: [
108+
// other routes ...
109+
],
110+
},
111+
],
112+
},
113+
]);
114+
115+
// error boundary
116+
import { useRouteError } from "react-router-dom";
117+
import * as Sentry from "@sentry/react";
118+
119+
export function YourCustomRootErrorBoundary() {
120+
const error = useRouteError() as Error;
121+
122+
React.useEffect(() => {
123+
Sentry.captureException(error);
124+
}, [error]);
125+
126+
return (
127+
<div>
128+
<h1>Ouch!</h1>
129+
</div>
130+
);
131+
}
132+
133+
```
134+
135+
85136
### Usage With `<Routes />` Component
86137

87138
If you're using the `<Routes />` component from `react-router-dom` to define your routes, wrap [`Routes`](https://reactrouter.com/en/main/components/routes) using `Sentry.withSentryReactRouterV6Routing`. This creates a higher order component, which will enable Sentry to reach your router context. You can also use `Sentry.withSentryReactRouterV6Routing` for `Routes` inside `BrowserRouter`. `MemoryRouter`, and `HashRouter` components:

0 commit comments

Comments
 (0)