Skip to main content

React Error Boundary Design Patterns

Implement React error boundaries with graceful degradation, error reporting, retry with backoff, and user-friendly fallback UIs.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt
You are a React reliability engineer specializing in error handling. Help me implement a comprehensive error boundary system for a enterprise dashboard application.

Step 1: Create a base ErrorBoundary class component in src/components/errors that catches JavaScript errors in its child component tree. Implement componentDidCatch to log error details (component stack, error message, timestamp, user context) to Sentry. Include a getDerivedStateFromError method that sets the error state for rendering the fallback UI.

Step 2: Build 4 specialized error boundary variants: PageErrorBoundary (full-page fallback with navigation), SectionErrorBoundary (inline fallback preserving surrounding content), WidgetErrorBoundary (silent degradation with a compact error indicator), and DataErrorBoundary (retry-focused fallback for data-fetching failures). Each variant should accept custom fallback components via render props.

Step 3: Implement an automatic retry mechanism in the DataErrorBoundary that attempts to re-render failed children up to 3 times with exponential backoff. Add a manual retry button in the fallback UI. Track retry attempts in the error report and escalate to a permanent error state after all retries are exhausted.

Step 4: Design a global error context using React Context that aggregates errors from all boundaries. Build an ErrorDashboard component (visible only in NODE_ENV=development) that displays all caught errors with their component stack traces, timestamps, and recovery status. This helps developers identify error-prone components during development.

Step 5: Create error boundary HOCs and hooks: withErrorBoundary(Component, options) for wrapping existing components, and useErrorHandler() for imperatively throwing errors from event handlers and async code that class-based error boundaries cannot catch natively.

Step 6: Write integration tests that verify each error boundary catches errors correctly, renders the appropriate fallback, reports to Sentry, and recovers when the error condition is resolved. Use React Testing Library to simulate component errors and assert on fallback UI rendering.

What this prompt does

This prompt makes the AI act as a React reliability engineer and design a layered error-boundary system for a [app_type] application. Instead of a single catch-all boundary, it builds a base ErrorBoundary in [components_directory] that logs to [error_service], then [boundary_count] specialized variants — page, section, widget, and data — each degrading at a different granularity. It adds retry-with-backoff for data failures, a dev-only error dashboard, helper HOCs and hooks, and integration tests.

The structure works because it matches the failure model of real React apps: a crash in one widget shouldn't blank an entire dashboard. By separating boundaries by scope, a failing chart can show a compact indicator while the rest of the page keeps working, and a full-page failure can still render navigation so users aren't stranded. The [max_retries] setting drives exponential backoff in the DataErrorBoundary, so a flaky API gets a chance to recover on its own before the error UI takes over, and the [dev_environment] flag keeps the diagnostic dashboard out of production. Routing logs to [error_service] means every caught error carries its component stack, message, timestamp, and user context, which is what makes the reports actually actionable.

When to use it

  • You're shipping a production React app and want graceful degradation instead of blank screens
  • A single unguarded render currently risks taking down a whole view or dashboard
  • You need different fallback behavior for full pages versus inline widgets
  • A data-fetching layer hits flaky APIs that often recover on retry
  • You want errors reported to [error_service] with component stacks attached
  • You're standardizing error handling across a growing component tree
  • You need to catch errors from event handlers and async code that boundaries miss natively

Example output

Expect a set of React components and supporting code: a base ErrorBoundary class with getDerivedStateFromError and componentDidCatch, the [boundary_count] named boundary variants accepting custom fallbacks via render props, the retry-with-backoff logic for DataErrorBoundary, a global error context plus an ErrorDashboard gated behind [dev_environment], a withErrorBoundary HOC, a useErrorHandler hook for imperative throwing, and React Testing Library tests that simulate component errors and assert on the rendered fallbacks. The output is structured as labeled steps so you can drop variants in incrementally rather than rewriting your tree at once.

Pro tips

  • Set [error_service] to whatever you actually use; the componentDidCatch logging shape changes between Sentry and other trackers
  • Keep [max_retries] low (the default 3 is sensible) — aggressive retries on a truly broken endpoint just delay the error UI
  • Remember class boundaries can't catch errors in event handlers or async code, which is exactly why the useErrorHandler hook exists
  • Gate the ErrorDashboard strictly behind [dev_environment] so stack traces never reach production users
  • Match [components_directory] to your project layout so generated imports resolve cleanly
  • Always wire up the integration tests; an error boundary that silently stops catching is worse than none

Frequently Asked Questions

Can React error boundaries catch errors in event handlers or async code?
No, class-based error boundaries only catch errors during rendering, lifecycle methods, and constructors of the components below them. That limitation is why this prompt includes a `useErrorHandler()` hook, which lets you imperatively forward errors from event handlers and async callbacks into a boundary.
Why use four boundary variants instead of one global boundary?
A single global boundary forces every error into the same full-page fallback, which is too blunt. The `[boundary_count]` variants let a widget fail quietly while a page-level crash shows navigation, so you degrade at the right granularity instead of blanking the whole screen.
Does the retry mechanism risk hammering a broken API?
It uses exponential backoff and caps attempts at `[max_retries]`, so the interval grows between tries and stops after a fixed count. After retries are exhausted it escalates to a permanent error state rather than looping, which protects a genuinely down service from repeated requests.
Which error tracking service does this assume?
It defaults to Sentry but is written around the `[error_service]` variable, so you can point it at any tracker. You'll adjust the `componentDidCatch` reporting call to match that service's SDK, since the data captured stays the same.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in React & Next.js Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support