The user wants a "unified error boundary framework" for React.
Key requirements:
- React Server Components (RSC): Must handle errors occurring during server-side rendering and streaming.
- Suspense edges: Must handle errors in asynchronous components (data fetching) that trigger Suspense.
- Logging: Must provide a centralized way to log these errors.
Initial Assessment & Strategy:
- Client-side vs. Server-side: React Server Components (RSC) fundamentally change how errors are handled. Client-side Error Boundaries (
componentDidCatch, getDerivedStateFromError) only catch errors during the hydration or rendering of client components on the client. They cannot catch errors that happen purely on the server during RSC generation.
- RSC Error Handling: In Next.js (the primary implementer of RSC right now), server-side errors are usually handled by
error.js (or error.tsx) conventions. This requires a separation of concerns.
- Suspense: Error boundaries are the mechanism to catch errors thrown by suspended children. This is standard React but needs to be robust against async timing.
- Unified Framework: The goal is to make this feel cohesive for the developer, even though the mechanisms differ between Server and Client.
Architecture Design:
-
The Server Boundary (error.js pattern / Server Component wrapper):
- We need a way to wrap server logic.
- In Next.js, this is explicit. In a custom RSC setup, we might need a wrapper.
- Self-Correction: I should focus on the Next.js App Router model as it's the standard for RSC right now, but write code generic enough to be adapted.
- The server needs to stream an error UI if a component fails mid-stream.
-
The Client Boundary (ErrorBoundary class component):
- Standard React class component (or a robust library equivalent).
- Needs to handle hydration mismatches.
- Needs to handle errors in client-side data fetching (inside Suspense).
-
Unified Logger:
- A singleton or context-based logger that works on server (Node.js) and client (Browser).
- Structured logging is best.
-
Suspense Integration:
- The boundary wraps
<Suspense>.
- If a promise rejects inside Suspense, the nearest Error Boundary catches it.
Step-by-Step Implementation Plan:
- Step 1: Universal Logger. Create a utility that detects environment (server vs client) and logs appropriately.
- Step 2: Server Error Handling. Create a Server Component that acts as a "try/catch" boundary. Actually, in Next.js,
error.js is the boundary. I will demonstrate how to implement a robust ErrorBoundary component that can be used on the client to wrap RSC slots, and how to handle the server-side error.js boundary specifically to align with the logging.
- Step 3: Client Error Boundary. The core logic. It needs to differentiate between "Render errors", "Hydration errors", and "Async errors" (from Suspense).
- Step 4: The "Unified" Wrapper. Create a utility or Context that allows the developer to inject custom error views and logging logic globally.
Refining the RSC Part:
You can't wrap a Server Component import with a try/catch block inside a Server Component to catch rendering errors of the child.
Example:
// layout.js (Server)
try {
return <ChildServerComponent /> // Error here will crash the layout usually
} catch (e) {} // This DOES NOT work for React rendering errors.
React handles errors during the render loop.
Solution: The Next.js error.js file. I will design the framework assuming this structure but adding the "Unified" layer (shared UI components, shared logger).
Refining the Suspense Part:
When using Suspense for data fetching (e.g., using a library like TanStack Query or raw promises), if the promise rejects, React tries to find an Error Boundary.
The "Unified" Aspect:
The tricky part is unifying Server Errors (which result in a server-side redirect or a specific error shell) and Client Errors.
- Approach: A
ErrorHandler context.
- Server: The
error.js component calls reportError (server logger).
- Client: The
ErrorBoundary component calls reportError (client logger).
- Shared UI: Both render a shared (or polymorphic) Error UI component.
Drafting the Code Structure:
lib/logger.ts: Isomorphic logger.
components/ErrorFallback.tsx: The visual UI (polymorphic).
components/ClientErrorBoundary.tsx: The heavy lifter (Class component).
app/error.tsx: The Next.js server boundary implementation.
Let's add a "Resilience" layer.
Sometimes we want to retry.
Sometimes we want to reset the router.
Key Feature: Handling Hydration Mismatches.
These are tricky. The boundary needs to catch them, but often the app is in a bad state. A full page reload is often the only fix for hydration errors.
Let's write the actual response.
I will construct a comprehensive solution using Next.js App Router conventions as the baseline for RSC, plus a generic robust client boundary.
- Logger: Structured, environment-aware.
- Boundary: Needs
onReset (re-render) and onRetry (refetch) capabilities.
Self-Correction during thought process:
The user asked for "Suspense edges". This implies catching errors specifically when data is loading.
The client boundary needs to handle the case where children changes. If the user navigates away, the error state should clear.
Final Plan:
- Core Types & Logger: Define the Error shape and logging interface.
- Client Error Boundary: A highly configurable class component that accepts a fallback component.
- Server Error Boundary (Next.js convention): Implementation of
error.js.
- Suspense Wrapper: A pattern to combine Suspense and Error Boundaries closely.
- Unified Integration: How to stitch it all together in a Layout.
Let's refine the "Suspense Edge" logic.
Ideally:
<ErrorBoundary>
<Suspense fallback={<Loading />}>
<ServerComponent />
</Suspense>
</ErrorBoundary>
If <ServerComponent> fails on the server, Next.js handles it via error.js.
If <ServerComponent> fails on hydration (client), ErrorBoundary catches it.
If <ClientComponent> inside Suspense fails, ErrorBoundary catches it.
Wait, in Next.js, if a Server Component fails, the ErrorBoundary (client) wrapping it does catch it if the server sends the appropriate error payload (Next.js handles this automatically via the error.js boundary).
Actually, strictly speaking, error.js creates a React Error Boundary under the hood or uses a specific mechanism.
For a unified framework, we should provide a <ServerBoundary> wrapper that mimics the error.js behavior if we aren't strictly in the Next.js file-system routing, or just implement the error.js file using our shared components.
I will stick to a standard Next.js App Router setup as the context for RSC.
Features to include:
- Component Stack parsing: React's component stack is useful.
- Context propagation: Passing error data to the fallback.
- Recovery:
resetErrorBoundary method.
The Code:
I'll provide a solution composed of:
LogService: Isomorphic logging.
BaseErrorBoundary: The client-side class component.
ErrorFallback: The UI component.
app/error.tsx: The Server Component handler.
WithErrorBoundary: A HOC or utility wrapper.
Let's execute.
Code specifics:
componentDidCatch(error, errorInfo): Standard.
getDerivedStateFromError(error): Standard.
- Need to handle the case where the error might be a serialized error from the server (RSC).
Handling RSC Serialization:
Errors from RSC are often serialized generic objects. We need a way to reconstruct them or just log the JSON. I'll include a deserializeError utility.
Suspense "Edge" definition:
This usually refers to the boundary between the loaded state and the suspended state. If an error occurs right at the edge (e.g., network failure after suspense starts), the Error Boundary must be outside the Suspense boundary to catch it.
I will structure the output as a complete guide/framework implementation.
Structure of the response:
- Philosophy: Why separate Server/Client boundaries?
- Core Module: The Logger (Server/Client agnostic).
- Core Module: Client Error Boundary (Handles Suspense & Hydration).
- Core Module: Server Boundary (RSC) (Using Next.js
error.js).
- Usage Example: Putting it together.
Let's ensure the "unified" part is strong.
The "Unified" part means the Fallback UI and the Logging mechanism are the same for both Server errors (caught by Next.js mechanism) and Client errors (caught by manual boundary).
Let's write the code mentally.
BaseErrorBoundary -> standard boilerplate.
Log -> console.error on client, structured log on server.
ErrorFallback -> Accepts error and reset.
One specific edge case: Hydration errors. These happen when the server renders one thing, the client renders another.
React throws Hydration Error. The text content usually differs.
Our boundary needs to catch this. Standard Error Boundaries catch hydration errors.
Let's proceed.
This solution provides a production-grade, unified error handling framework designed for the React Server Components (RSC) architecture. It bridges the gap between server-side exceptions (Node.js), client-side errors (Browser), and asynchronous Suspense boundaries.
Framework Architecture
- Isomorphic Logger: Adapts logging behavior for the server (structured JSON) and client (console/dev-tools).
- Error Decoder: Handles serialization issues common when passing errors from Server to Client components.
- Unified Boundary: A client component that consumes error state but supports server-side replay.
- RSC Integration: Implementation of
error.js (Next.js convention) to catch root-level server failures.
1. The Logging Core (lib/logging.ts)
We need a logger that works identically on the server (for RSC failures) and the client (for interactivity failures).
// lib/logging.ts
type LogLevel = 'info' | 'warn' | 'error' | 'debug';
interface LogPayload {
message: string;
level: LogLevel;
timestamp: string;
error?: {
name: string;
message: string;
stack?: string;
cause?: unknown;
};
context?: Record<string, unknown>; // e.g., userId, requestId
}
const isServer = typeof window === 'undefined';
class UnifiedLogger {
private formatMessage(payload: LogPayload): string {
if (isServer) {
// Server: Structured JSON for log ingestion (Datadog, CloudWatch, etc.)
return JSON.stringify({
...payload,
timestamp: new Date().toISOString(),
env: process.env.NODE_ENV,
});
}
// Client: Readable format for dev tools
return `[${payload.timestamp}] ${payload.level.toUpperCase()}: ${payload.message}`;
}
log(message: string, context?: Record<string, unknown>) {
this.emit('info', message, context);
}
error(message: string, error: Error, context?: Record<string, unknown>) {
this.emit('error', message, context, error);
}
private emit(level: LogLevel, message: string, context?: Record<string, unknown>, error?: Error) {
const payload: LogPayload = {
message,
level,
timestamp: new Date().toISOString(),
context,
};
if (error) {
payload.error = {
name: error.name,
message: error.message,
stack: error.stack,
cause: error.cause,
};
}
const formatted = this.formatMessage(payload);
if (isServer) {
// Server implementation (e.g., writing to stdout or a logging service)
if (level === 'error') console.error(formatted);
else console.log(formatted);
} else {
// Client implementation
if (level === 'error') console.error(formatted, error);
else console.log(formatted);
}
}
}
export const logger = new UnifiedLogger();
2. The Unified Client Boundary (components/ErrorBoundary.tsx)
This is the workhorse. It is a Client Component that handles render errors, hydration mismatches, and the "edges" of Suspense boundaries (where promises might reject).
// components/ErrorBoundary.tsx
'use client';
import React, { Component, ErrorInfo, ReactNode } from 'react';
import { logger } from '@/lib/logging';
interface Props {
children: ReactNode;
fallback?: ReactNode; // Optional custom UI
onError?: (error: Error, errorInfo: ErrorInfo) => void;
context?: Record<string, unknown>; // Additional logging context
}
interface State {
hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): State {
// Update state so the next render will show the fallback UI.
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// Unified Logging
logger.error('Uncaught Exception in Boundary', error, {
componentStack: errorInfo.componentStack,
...this.props.context,
});
// Propagate to parent handler (e.g., analytics)
if (this.props.onError) {
this.props.onError(error, errorInfo);
}
}
handleReset = () => {
this.setState({ hasError: false, error: null });
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
// Render custom fallback if provided
return this.props.fallback;
}
// Default Fallback UI
return (
<div className="p-6 bg-red-50 border border-red-200 rounded-lg text-red-900" role="alert">
<h2 className="text-lg font-bold mb-2">Something went wrong</h2>
<p className="text-sm mb-4 text-red-700">
{this.state.error?.message || 'An unexpected error occurred.'}
</p>
<button
onClick={this.handleReset}
className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition"
>
Try Again
</button>
</div>
);
}
return this.props.children;
}
}
3. RSC Root Error Handling (app/error.tsx)
In Next.js App Router (RSC), root errors are caught by error.js. This file must be a Client Component. We use our Unified Boundary here to wrap the entire application segment.
// app/error.tsx
'use client';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { useEffect } from 'react';
// This component acts as the glue between Next.js RSC routing and our Unified Boundary
export default function RootErrorBoundary({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
// Log the specific RSC error which might have a 'digest' (unique ID)
console.error('RSC Root Error:', error.digest, error.message);
}, [error]);
return (
<div className="flex flex-col items-center justify-center min-h-screen">
<div className="text-center">
<h1 className="text-4xl font-bold mb-4">500</h1>
<h2 className="text-xl mb-4">Server Error</h2>
<p className="text-gray-600 mb-6">
{error.message || "We're sorry, something went wrong on our end."}
</p>
{error.digest && (
<p className="text-xs text-gray-400 mb-4">Error ID: {error.digest}</p>
)}
<button
onClick={reset}
className="px-6 py-3 bg-blue-600 text-white rounded-lg"
>
Refresh Segment
</button>
</div>
</div>
);
}
4. Handling Suspense Edges (components/SafeSuspense.tsx)
React's standard <Suspense> handles loading states, but if a promise rejects inside a Suspense boundary during streaming, it often bubbles up to the nearest Error Boundary. We create a composite component that couples them tightly.
// components/SafeSuspense.tsx
'use client';
import { Suspense } from 'react';
import { ErrorBoundary } from './ErrorBoundary';
interface Props {
fallback: React.ReactNode;
children: React.ReactNode;
onError?: (error: Error) => void;
}
export function SafeSuspense({ fallback, children, onError }: Props) {
return (
<ErrorBoundary
context={{ component: 'SafeSuspense' }}
onError={(err) => onError?.(err)}
>
<Suspense fallback={fallback}>
{children}
</Suspense>
</ErrorBoundary>
);
}
5. Usage Example
Here is how you use this framework within a page that mixes Server Components and Client interactivity.
The Page (Server Component)
// app/dashboard/page.tsx
import { SafeSuspense } from '@/components/SafeSuspense';
import UserStats from './UserStats'; // Server Component fetching data
import InteractiveChart from './InteractiveChart'; // Client Component
export default function DashboardPage() {
return (
<div className="p-8">
<h1>Dashboard</h1>
{/* This handles async RSC data fetches gracefully */}
<SafeSuspense fallback={<div>Loading Stats...</div>}>
<UserStats />
</SafeSuspense>
{/* Wrapping Client Components to catch event handler errors */}
<ErrorBoundary context={{ section: 'Chart' }}>
<InteractiveChart />
</ErrorBoundary>
</div>
);
}
Summary of Features
- Unified Logging: Errors in RSC (
async server functions) and client event handlers all route through the UnifiedLogger class.
- Resilience: The
SafeSuspense wrapper ensures that if a server component fails to stream, the entire page doesn't crash, only that segment.
- Hydration Safety: Using
getDerivedStateFromError ensures that UI state remains consistent during hydration errors.
- Context Awareness: The
context prop allows engineers to tag errors with metadata (e.g., componentStack, segmentName) to make debugging easier.