Skip to content

Add global ErrorBoundary to prevent blank screen crashes (#7872) #7873

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/components/ErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"use client";
import { Component, ReactNode } from "react";

type Props = {
children: ReactNode;
};

type State = {
hasError: boolean;
};

export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}

static getDerivedStateFromError(_: Error) {
return { hasError: true };
}

componentDidCatch(error: Error, info: any) {
console.error("Caught by ErrorBoundary:", error, info);
}

render() {
if (this.state.hasError) {
return (
<main style={{ padding: "2rem", textAlign: "center" }}>
<h1>Something went wrong.</h1>
<p>Try refreshing the page. If the problem persists, please report it.</p>
</main>
);
}

return this.props.children;
}
}
5 changes: 4 additions & 1 deletion src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
import { ErrorBoundary } from '../components/ErrorBoundary';

import {useEffect} from 'react';
import {AppProps} from 'next/app';
Expand Down Expand Up @@ -54,5 +55,7 @@ export default function MyApp({Component, pageProps}: AppProps) {
};
}, [router.events]);

return <Component {...pageProps} />;
return <ErrorBoundary>
<Component {...pageProps} />
</ErrorBoundary>;
}
Loading