From 2fe22856da07c7c2833a60b31df4046dc004b1ed Mon Sep 17 00:00:00 2001 From: Charly Gomez Date: Thu, 19 Sep 2024 16:30:33 +0200 Subject: [PATCH] docs(react): Add error boundary docs for react-router (#11326) --- .../guides/react/features/react-router.mdx | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/docs/platforms/javascript/guides/react/features/react-router.mdx b/docs/platforms/javascript/guides/react/features/react-router.mdx index b37aa220925fd..a856e1b45bcb4 100644 --- a/docs/platforms/javascript/guides/react/features/react-router.mdx +++ b/docs/platforms/javascript/guides/react/features/react-router.mdx @@ -82,6 +82,57 @@ You can instrument [`createMemoryRouter`](https://reactrouter.com/en/main/router +### Custom Error Boundaries + +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. + + +Note, that this only applies to render method and lifecycle errors since React doesn't need error boundaries to handle errors in event handlers. + + +To send errors to Sentry while using a custom error boundary, use the `Sentry.captureException` method: + +```jsx {11, 28} +// router setup +const sentryCreateBrowserRouter = wrapCreateBrowserRouter(createBrowserRouter); +const router = sentryCreateBrowserRouter([ + { + path: "/", + element: , + children: [ + { + path: "", + element: , + errorElement: , + children: [ + // other routes ... + ], + }, + ], + }, +]); + +// error boundary +import { useRouteError } from "react-router-dom"; +import * as Sentry from "@sentry/react"; + +export function YourCustomRootErrorBoundary() { + const error = useRouteError() as Error; + + React.useEffect(() => { + Sentry.captureException(error); + }, [error]); + + return ( +
+

Ouch!

+
+ ); +} + +``` + + ### Usage With `` Component If you're using the `` 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: