Server Error Handling:
Since server components are rendered on the server, we can catch errors in the server rendering process and then pass the error to a logging mechanism and then render an error component. But the server component itself cannot have an error boundary because it's not a client component.
However, in frameworks like Next.js, we can use error.js (or error.tsx) file in the app directory to handle errors for a segment. But that is framework-specific.
We want a solution that is more portable? Or at least we can provide a way to log errors from server components.
Idea: We can create a higher-order function or a wrapper for server components that catches errors and then logs them and returns a fallback UI. But again, we cannot use state in server components.
Alternatively, we can use a try-catch in the server component and then return a special React element that indicates an error? But then we need to handle that in the client.
Actually, when a server component throws an error, the entire segment (or the nearest error boundary in the client) will catch it? Because the server component's output is streamed to the client and if there's an error, the server will send an error response for that part.
In Next.js, if a server component throws, the error is caught by the nearest error.js file (which is a client component). So we can rely on that.
So the unified approach:
- For client components: use
ClientErrorBoundary to catch errors and log and show fallback.
- For server components: we don't wrap them in an error boundary because they are server components. Instead, we let the framework handle the error (which will be caught by the nearest client error boundary, because the server component's error will be propagated to the client as a React error).
But wait: when a server component throws, the error is not caught by a client error boundary that wraps the server component? Actually, in React 18 with Suspense, if a server component throws, the error will be caught by the nearest error boundary that is a client component and that is above the server component in the tree.
So we can have:
<ClientErrorBoundary fallback={<ErrorComponent />}>
<ServerComponent />
</ClientErrorBoundary>
But note: ServerComponent is a server component, and the ClientErrorBoundary is a client component. The server component will be rendered on the server and if it throws, the error will be caught by the client error boundary? According to React documentation, error boundaries work for errors in the render phase of their child components, regardless of whether the child is a server or client component.
However, note that the server component is rendered on the server, so the error occurs on the server. But the error boundary is on the client. How does that work?
Actually, when using React Server Components, the server component's code runs on the server. If it throws, the server will catch the error and then the React server will send an error response for that component to the client. The client will then see the error and the error boundary will catch it? I think so, because the error boundary is designed to catch errors during rendering, and the rendering of the server component's result (which is a React element) on the client might be where the error is caught? This is a bit unclear.
Let me clarify: In the React Server Components model, the server component is executed on the server and produces a serialized representation (React elements) that is sent to the client. If the server component throws, the server will catch that and then the server will send an error placeholder (like an error boundary on the server?) but actually, the server will send an error response that the client will then treat as an error in the rendering of that component? And then the client error boundary will catch it?
According to the React documentation: "Error boundaries work for errors in the render phase of their child components, regardless of whether the child is a server or client component."
So if a server component throws during its render on the server, the error will be caught by the nearest error boundary (which could be a client error boundary) when the client tries to render the component? Actually, the server component's error happens on the server, but the error boundary is on the client. How does the error propagate?
I think the error is serialized and sent to the client, and then the client error boundary will catch it when trying to render the component that had the error? But the server component is not rendered on the client, so the error boundary on the client might not catch the server component's error.
After reading:
- When a server component throws, the entire server component tree that is being rendered on the server will be replaced by the nearest error boundary (which must be a client component) in the client tree. So the error boundary must be in the client tree and above the server component in the tree.
Example:
In a client component:
// app/page.js (client component by default in Next.js 13+ if not using 'use client')
import ServerComponent from './ServerComponent';
export default function Page() {
return (
<div>
<ClientErrorBoundary fallback={<div>Error in server component</div>}>
<ServerComponent />
</ClientErrorBoundary>
</div>
);
}
If ServerComponent throws on the server, then the error will be caught by ClientErrorBoundary and the fallback will be shown.
So we can create a ClientErrorBoundary that works for both client and server components.
But note: the ClientErrorBoundary must be a client component (because it uses useState and useEffect to catch errors). And it must be placed in the client component tree.
So our plan:
-
Create a ClientErrorBoundary component that:
- Uses
React.ErrorBoundary (from 'react' or from 'react-error-boundary'? We'll use the one from 'react' in React 18+).
- Provides a way to log errors (using a custom
onError function).
- Accepts a
fallback prop and an onError prop.
-
We'll also provide a way to log errors from server components that are caught by this boundary. Since the error boundary runs on the client, we have the error object and we can log it.
However, note that the error from a server component might be a serialized error (with limited information). But the error boundary will receive the error object.
Implementation of ClientErrorBoundary:
We can use the built-in ErrorBoundary component from React 18, but note that it is experimental and might change. Alternatively, we can use the react-error-boundary library which is more stable and provides more features.
But to avoid external dependencies, we can implement a simple error boundary with a class component (because hooks for error boundaries are not yet stable in React 18). However, React 18 does have an ErrorBoundary component in the react package but it's experimental.
Let's use the class component approach for maximum compatibility and stability.
Alternatively, we can use the react-error-boundary library which is widely used. But the problem says "engineer", so we can build our own.
We'll build a class component error boundary and then wrap it in a client component that accepts the onError and fallback props.
Steps for the error boundary class:
static getDerivedStateFromError(error): to set state to show fallback.
componentDidCatch(error, errorInfo): to log the error.
But note: componentDidCatch is only called for errors in the render phase, lifecycle methods, and constructors of the child components. It won't catch errors in event handlers, async code, etc. So we might need to also catch errors in event handlers? But that's not the job of an error boundary.
We'll stick to rendering errors.
We'll create:
// ClientErrorBoundary.jsx
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null, errorInfo: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
this.setState({ errorInfo });
if (this.props.onError) {
this.props.onError(error, errorInfo);
} else {
// Default logging
console.error('ErrorBoundary caught an error', error, errorInfo);
}
}
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
// Default fallback
return (
<div>
<h2>Something went wrong.</h2>
<pre>{this.state.error && this.state.error.toString()}</pre>
<pre>{this.state.errorInfo?.componentStack}</pre>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
Then we create a client component that uses this class:
// ClientErrorBoundary.jsx
'use client';
import ErrorBoundaryClass from './ErrorBoundaryClass';
export default function ClientErrorBoundary({ children, fallback, onError }) {
return (
<ErrorBoundaryClass fallback={fallback} onError={onError}>
{children}
</ErrorBoundaryClass>
);
}
But wait, we want to log errors from server components as well. The above error boundary will catch errors from server components because they are children? Actually, the server component is a child of the error boundary, and when it throws on the server, the error will be caught by this client error boundary? As per React documentation, yes.
However, note that the error boundary must be in the client component tree and the server component must be its child (in the React element tree). And the server component must be rendered on the server and then the error occurs on the server? But the error boundary is on the client.
Actually, the error boundary will catch the error when the client tries to render the server component's output? I think the error is caught on the server and then the server sends an error response that the client then uses to show the error boundary.
But the above error boundary is a class component and it will catch errors in its children, regardless of whether the child is a server or client component.
So we are good.
But what about Suspense? The error boundary also catches errors in Suspense components? Yes, because Suspense components are also children.
However, note that if a Suspense boundary throws (because a promise rejects) then the error boundary will catch that too? Actually, Suspense boundaries are for showing a fallback while loading, but if a promise rejects, it becomes an error and then the error boundary will catch it.
But note: React has a concept of "Suspense edges" which are boundaries that catch errors in their children and show a fallback. But the error boundary we built also catches errors. So we have two layers? Actually, Suspense boundaries are for loading states and error boundaries are for errors. They are separate.
So our error boundary will catch errors that occur during rendering of its children, including when a Suspense boundary throws because of a rejected promise.
But what if we want to catch errors in a Suspense boundary and then show a different fallback? We can wrap the Suspense boundary with an error boundary.
Example:
<ClientErrorBoundary fallback={<ErrorFallback />}>
<Suspense fallback={<Loading />}>
<SomeComponent />
</Suspense>
</ClientErrorBoundary>
If SomeComponent throws, the error boundary catches it. If the Suspense boundary throws because a promise rejected, then the error boundary also catches it.
But note: the Suspense boundary itself does not throw, it catches the promise and shows the loading fallback. Only when the promise rejects, then the Suspense boundary will throw and the error boundary will catch.
So we are covered.
However, we might want to have a separate way to handle errors in Suspense boundaries? Actually, the error boundary is the right place to catch any error in the tree.
So our ClientErrorBoundary should be able to handle:
- Errors in client components.
- Errors in server components (propagated from server to client).
- Errors in Suspense boundaries (when a promise rejects).
Now, what about logging? We want to log errors from both client and server components. The error boundary will get the error and errorInfo and we can log them.
But note: the error from a server component might be a serialized error, so we might not get the full stack trace. That's a limitation.
We can also log the error in the server? But our error boundary is on the client. So we are only logging on the client.
If we want to log server-side errors, we might need to do it on the server. But the problem says "unified error boundary framework", so maybe we want to log errors from both server and client in the same way.
How about: when a server component throws, the server will log the error? But then we are logging twice? We want to log only once.
Actually, the error boundary on the client will catch the error and we can log it. But the error might have already been logged on the server by the framework. We might want to avoid duplicate logging.
We can design our framework to have a logging function that is called by both the server and the client? But we are building a client component.
Alternatively, we can have a logging service that is called by the error boundary on the client and also by the server when a server component throws? But then we need to integrate with the server framework.
Since we are building a framework that works with React Server Components, we might need to provide a way to log errors on the server as well.
But the problem says "logging", so we can at least log on the client. And for server-side, we can rely on the framework's logging and then also log on the client? That would be duplicate.
Let's think: In Next.js, when a server component throws, the error is logged by Next.js and then the error boundary on the client will also log. So we get duplicate.
We can avoid duplicate by having a flag in the error that says it's already logged? But we don't control the server.
Alternatively, we can decide to only log on the client and not on the server? But then we lose the server-side context.
Since the requirement is for a unified framework, we might want to have a consistent logging mechanism on both server and client.
However, note that the error boundary is a client component, so it can only run on the client.
So for server components, we cannot log on the server from the error boundary because the error boundary is on the client.
Therefore, we have two options:
Option 1: Log only on the client, and accept that server errors will be logged on the client (with potentially less information).
Option 2: Provide a way to log on the server as well. How? We can create a server-side error boundary? But server components cannot have error boundaries.
Actually, we can create a higher-order function for server components that catches errors and then logs them and re-throws? But then the error will still be caught by the client error boundary and logged again.
Alternatively, we can have a logging function that is called by both the server and the client, and we can avoid duplicate by having a unique error ID? That's complex.
Given the complexity, and since the problem says "unified", maybe we focus on client-side logging and accept that server-side errors will be logged by the framework and then again by our error boundary? That might be acceptable for now.
But we can also provide an option to disable logging in the error boundary for server errors? We don't know if the error is from server or client.
Actually, the error object from a server component might have a property that indicates it's from the server? Not standard.
So let's stick to client-side logging only, and if the user wants to log server errors, they should do it on the server.
We can design our error boundary to have an onError callback that is called for every error, and then the user can decide to log or not, and also to send to a server logging endpoint.
So the user can do:
<ClientErrorBoundary
onError={(error, errorInfo) => {
// Log to an external service
logErrorToService(error, errorInfo);
}}
>
...
</ClientErrorBoundary>
And if they want to avoid duplicate logging for server errors (if the framework already logs them), they can conditionally log.
But we don't have a way to know if the error is from the server.
Alternatively, we can provide two callbacks: onClientError and onServerError. But again, we don't know the source.
So we leave it to the user to handle.
Now, what about Suspense edges? We said that error boundaries catch errors in Suspense boundaries when a promise rejects. But what about when a Suspense boundary is used for loading? That's not an error.
So we are good.
Let's write the code:
We'll have:
ClientErrorBoundary.jsx: the client component that uses the class error boundary.
ErrorBoundaryClass.js: the class component (we can put it in the same file or separate).
But to keep it simple, we can put everything in one file.
However, note that the class component is a client component? Actually, the class component doesn't use client-specific hooks, so it can be used in both client and server? But error boundaries are only for client components because they use state and componentDidCatch which are client-only.
So we mark the ClientErrorBoundary as a client component.
Let's code:
File: ClientErrorBoundary.jsx
'use client';
import React, { Component } from 'react';
class ErrorBoundaryClass extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null, errorInfo: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
this.setState({ errorInfo });
if (this.props.onError) {
this.props.onError(error, errorInfo);
} else {
// Default logging
console.error('ErrorBoundary caught an error', error, errorInfo);
}
}
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
// Default fallback
return (
<div>
<h2>Something went wrong.</h2>
<pre>{this.state.error && this.state.error.toString()}</pre>
<pre>{this.state.errorInfo?.componentStack}</pre>
</div>
);
}
return this.props.children;
}
}
export default function ClientErrorBoundary({ children, fallback, onError }) {
return (
<ErrorBoundaryClass fallback={fallback} onError={onError}>
{children}
</ErrorBoundaryClass>
);
}
Now, we can use this ClientErrorBoundary to wrap any part of our app (client or server components) and it will catch errors and log them.
But note: the ClientErrorBoundary must be used in a client component. So if we want to wrap a server component, we must be in a client component.
Example:
// app/page.js (client component)
import ClientErrorBoundary from './ClientErrorBoundary';
import ServerComponent from './ServerComponent';
export default function Page() {
return (
<ClientErrorBoundary fallback={<div>Error</div>} onError={logError}>
<ServerComponent />
</ClientErrorBoundary>
);
}
But what if we want to wrap a whole segment that includes server components? We can do:
// app/layout.js (client component)
import ClientErrorBoundary from './ClientErrorBoundary';
export default function Layout({ children }) {
return (
<ClientErrorBoundary fallback={<div>Layout error</div>} onError={logError}>
{children}
</ClientErrorBoundary>
);
}
But note: the layout might be a server component by default in Next.js? Actually, in Next.js 13, layout.js is a server component by default. So we cannot use a client component as the layout? We can, but then the layout becomes a client component and we lose the benefits of server components for the layout.
Alternatively, we can make the layout a server component and then wrap the children with the error boundary? But the error boundary is a client component, so we cannot use it in a server component.
So we have a problem: if we want to wrap a server component tree (which includes server components) with an error boundary, we must do it in a client component. That means we have to make the parent a client component.
But then the parent (and its entire subtree) becomes client components, which we might not want.
Alternatively, we can use the framework's built-in error boundary (like error.js in Next.js) for server components and then use our ClientErrorBoundary only for client components.
But the requirement is for a unified framework.
So maybe we provide two components:
ClientErrorBoundary for client components (which uses the class component above).
ServerErrorBoundary? But we cannot have a server error boundary because server components cannot have state.
So we are forced to use the framework's error handling for server components and our client error boundary for client components.
But wait: the React documentation says that error boundaries catch errors in server components too, but the error boundary must be a client component and in the client tree above the server component.
So we can use the same ClientErrorBoundary for both, but we must place it in a client component that is above the server component in the tree.
That means we have to make the parent a client component. This might be acceptable for some parts of the app but not for others.
In Next.js, we can use export const dynamic = 'force-dynamic'; to make a server component become a client component? Not exactly.
Actually, in Next.js, if we want to use a client component in a server component, we can do:
// app/page.js (server component)
import ClientErrorBoundary from './ClientErrorBoundary';
export default function Page() {
return (
<ClientErrorBoundary fallback={<div>Error</div>}>
<div>This is a server component, but the error boundary is a client component.</div>
</ClientErrorBoundary>
);
}
But this will make Page a client component because it uses a client component? Actually, in Next.js, if a server component imports a client component, it becomes a client component? No, the server component can still be a server component and render a client component. The client component will be rendered on the client.
But the error boundary is a client component, so it will be rendered on the client. And the server component (the div) will be rendered on the server and then hydrated on the client.
So the error boundary will catch errors in the div? The div is a server component and it doesn't throw. But if we have a server component that throws, then the error boundary will catch it? Yes, because the server component is a child of the error boundary.
So we can use ClientErrorBoundary in a server component? Actually, the server component is allowed to render client components. So we can do:
// app/page.js (server component)
import ClientErrorBoundary from './ClientErrorBoundary';
import ServerComponent from './ServerComponent';
export default function Page() {
return (
<ClientErrorBoundary fallback={<div>Error</div>}>
<ServerComponent />
</ClientErrorBoundary>
);
}
But wait: the ClientErrorBoundary is a client component, and we are using it in a server component. That is allowed? In Next.js, yes, but the server component will be rendered on the server and the client component will be rendered on the client. So the error boundary will be on the client, and the server component will be rendered on the server and then its output will be sent to the client. If the server component throws, the error will be caught by the error boundary on the client.
So this works.
But note: the server component must be a child of the error boundary in the React tree. And the error boundary must be a client component.
So we can use ClientErrorBoundary anywhere, even in server components, as long as we are okay with the error boundary being a client component.
However, if we use ClientErrorBoundary in a server component, the entire subtree from the error boundary down will be client components? No, the error boundary is a client component, but its children can be server components. The error boundary will wrap the server component and catch its errors.
So we are good.
Now, what about logging? We want to log errors from both client and server components. The error boundary will log the error it catches, regardless of the source.
But note: the error from a server component might be missing some information (like stack trace) because it's serialized. So we might want to log on the server as well? But we don't have a server-side error boundary.
We can try to catch errors in server components by using a try-catch in the server component and then logging and re-throwing? But then the error will be caught by the error boundary and logged again.
We can do:
// ServerComponent.js (server component)
export default function ServerComponent() {
try {
// ... code that might throw
} catch (error) {
// Log on the server
console.error('ServerComponent error', error);
throw error; // re-throw so the error boundary catches it
}
}
But then we are logging twice (once on server and once on client). We can avoid the client log by not having the error boundary log? But the error boundary is there to catch and show a fallback.
Alternatively, we can have a logging service that is called only once. We can have a unique error ID and then on the client we check if we already logged? That's complex.
Given the constraints, we might accept duplicate logging for server errors, or we can design our error boundary to not log if the error is from the server? But we don't know.
So we leave it to the user to decide. They can provide an onError callback that checks the error and decides whether to log.
Now, what about Suspense? We are already catching errors in Suspense boundaries because they are children.
But what if we want to catch errors in a Suspense boundary and then show a different fallback? We can wrap the Suspense boundary with the error boundary.
So our framework is:
- A client component
ClientErrorBoundary that uses a class error boundary to catch errors in its children (including server components and Suspense boundaries) and logs them and shows a fallback.
We can also extend it to have a way to reset the error state? Yes, we can add a reset function.
But the problem doesn't specify.
Let's add a resetError function that can be called to reset the error state. We can pass it as a prop to the fallback? Or we can provide it via context? The react-error-boundary library provides a resetKeys prop and a reset function via context.
We can do something similar.
We'll add:
resetKeys: an array of values that when changed, will reset the error boundary.
- Also, we can provide a
reset function via context so that the fallback can reset the error.
But let's keep it simple for now and just have the fallback prop. The user can implement their own reset by using state and a reset function.
Alternatively, we can extend our class to have a reset method and then expose it via a ref? That's more complex.
Since the problem doesn't specify, we'll skip reset for now.
Now, we have a basic error boundary.
But what about logging for client-side errors that are not caught by the error boundary? For example, errors in event handlers or async code. We can provide a separate global error handler? But that's outside the scope of the error boundary.
The error boundary only catches errors during rendering, lifecycle methods, and constructors.
So we can also provide a way to catch global errors (like window.onerror and unhandledrejection) and then log them? But that's separate.
We can create a separate utility for that.
But the problem says "unified error boundary framework", so we are focusing on error boundaries.
We can also note that the error boundary will catch errors in the render phase, but not in event handlers, async code, etc. So we might want to combine with global error handlers.
We can create a higher-level component that sets up global error handlers and also uses the error boundary? But that might be overkill.
Let's stick to the error boundary for now.
Summary:
We have created a ClientErrorBoundary that:
- Can be used in both client and server component trees (as long as it is in a client component, which it is because it's marked with 'use client').
- Catches errors in its children (including server components and Suspense boundaries).
- Logs errors via
onError or by default to console.
- Shows a fallback UI when an error occurs.
This is a unified error boundary for React Server Components and client components.
However, note that for server components, the error boundary must be in the client tree above the server component. And the server component must be a direct or indirect child of the error boundary.
We are done.
But wait, what about multiple error boundaries? We can nest them. The inner error boundary will catch errors first.
That's how error boundaries work.
Now, let's consider TypeScript.
We can write it in TypeScript for better type safety.
But the problem doesn't specify, so we can leave it in JavaScript.
However, since we are engineering a framework, we should provide TypeScript types.
Let's convert to TypeScript:
We'll create ClientErrorBoundary.tsx:
'use client';
import React, { Component, ErrorInfo, ReactNode } from 'react';
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode;
onError?: (error: Error, errorInfo: ErrorInfo) => void;
}
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
errorInfo: ErrorInfo | null;
}
class ErrorBoundaryClass extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: null, errorInfo: null };
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
this.setState({ errorInfo });
if (this.props.onError) {
this.props.onError(error, errorInfo);
} else {
console.error('ErrorBoundary caught an error', error, errorInfo);
}
}
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div>
<h2>Something went wrong.</h2>
<pre>{this.state.error && this.state.error.toString()}</pre>
<pre>{this.state.errorInfo?.componentStack}</pre>
</div>
);
}
return this.props.children;
}
}
export function ClientErrorBoundary(props: ErrorBoundaryProps) {
return <ErrorBoundaryClass {...props} />;
}
But note: we are using a class component inside the function component. We can also export the class directly? But we want the default export to be the function component.
Alternatively, we can write the function component with hooks? But the error boundary hooks are experimental.
So we stick with the class.
Now, we have a TypeScript version.
But wait, the ErrorInfo type is from React. We are using errorInfo?.componentStack which is a string.
This should work.
Now, what about the fallback prop? It can be a ReactNode.
We are done.
However, note that the ClientErrorBoundary function component doesn't use any state, so it's just a wrapper.
We can also export the class as a named export? But the problem says "framework", so we want a simple API.
We'll export the function as default.
Now, we have a unified error boundary.
But we haven't addressed the logging of server-side errors that occur outside of the error boundary? For example, in a server component that is not wrapped by an error boundary? Then the framework will handle it (show an error page) and we might not log it with our logging function.
We can only log errors that are caught by our error boundary.
So if we want to log all server errors, we need to wrap every server component with our error boundary? That's not practical.
Alternatively, we can rely on the framework's error page and then also set up a global error handler on the server? But that's framework-specific.
Since the requirement is for a unified error boundary framework, we are providing a client-side error boundary that works for both server and client components, but it must be placed in the tree.
We can also provide a higher-order component (HOC) or a wrapper for server components that automatically wraps them with the error boundary? But then the HOC would be a client component? We cannot have a server component HOC that uses a client component.
So we cannot automatically wrap server components.
Therefore, the user must manually wrap the parts they want to catch with ClientErrorBoundary.
This is similar to how error boundaries are used in React.
So we are done.
Let me write the final code in TypeScript.
We'll have:
File: ClientErrorBoundary.tsx
'use client';
import React, { Component, ErrorInfo, ReactNode } from 'react';
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode;
onError?: (error: Error, errorInfo: ErrorInfo) => void;
}
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
errorInfo: ErrorInfo | null;
}
class ErrorBoundaryClass extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: null, errorInfo: null };
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
this.setState({ errorInfo });
if (this.props.onError) {
this.props.onError(error, errorInfo);
} else {
console.error('ErrorBoundary caught an error', error, errorInfo);
}
}
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div>
<h2>Something went wrong.</h2>
<pre>{this.state.error && this.state.error.toString()}</pre>
<pre>{this.state.errorInfo?.componentStack}</pre>
</div>
);
}
return this.props.children;
}
}
export function ClientErrorBoundary(props: ErrorBoundaryProps) {
return <ErrorBoundaryClass {...props} />;
}
We can also provide a default export as a function component.
Now, we can use it as:
import ClientErrorBoundary from './ClientErrorBoundary';
// In a client component or a server component (because it uses a client component)
function App() {
return (
<ClientErrorBoundary
fallback={<div>Oops, something went wrong!</div>}
onError={(error, errorInfo) => {
// Log to an external service
logErrorToService(error, errorInfo);
}}
>
<SomeComponent />
</ClientErrorBoundary>
);
}
This should work for both client and server components.
However, note that the onError callback will be called on the client, so if we want to log server errors on the server, we cannot do it from here.
But we can send the error to a server logging endpoint from the client.
So we can log all errors (client and server) to the same service by sending them from the client.
That might be acceptable.
We are done.
But wait, what about the errorInfo.componentStack? For server components, the componentStack might not be the same as on the client? It will be the stack from the server? Actually, the errorInfo is generated on the client when the error is caught? Or is it serialized from the server?
According to React, the errorInfo from a server component error will have a componentStack that shows the component tree on the server? I think so.
So we get the server component stack.
This is good.
Now, we have a unified error boundary.
However, note that the error boundary will not catch errors in async code (like useEffect, event handlers, promises). We can extend it to catch unhandled rejections and global errors? But that's beyond the scope of an error boundary.
We can provide a separate utility for that.
But the problem says "error boundary framework", so we focus on boundaries.
We are done.
Let me know if you have any questions.
I'll design a comprehensive error boundary framework that handles React Server Components, Suspense boundaries, and provides robust logging capabilities. This is a production-ready solution with TypeScript support.