Skip to content

Instantly share code, notes, and snippets.

@markerikson
Created July 1, 2021 13:43
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save markerikson/780bf48175b97049713e1d96b2ebe799 to your computer and use it in GitHub Desktop.
Save markerikson/780bf48175b97049713e1d96b2ebe799 to your computer and use it in GitHub Desktop.
Next.js ErrorBoundary example
export default function MyApp({ Component, pageProps }: { Component: any; pageProps: any }) {
// ReactErrorBoundary doesn't pass in the component stack trace.
// Capture that ourselves to pass down via render props
const [errorInfo, setErrorInfo] = useState<React.ErrorInfo | null>(null);
return (
<React.Fragment>
<ErrorBoundary
onError={(error, info) => {
if (process.env.NODE_ENV === 'production') {
uploadErrorDetails(error, info);
}
setErrorInfo(info);
}}
fallbackRender={fallbackProps => {
return <AppErrorFallback {...fallbackProps} errorInfo={errorInfo} />;
}}
>
<Component {...pageProps} />;
</ErrorBoundary>
</React.Fragment>
);
}
import React from 'react';
import Jumbotron from 'react-bootstrap/Jumbotron';
import Alert from 'react-bootstrap/Alert';
import Button from 'react-bootstrap/Button';
import { FallbackProps } from 'react-error-boundary';
interface AEFProps extends FallbackProps {
errorInfo: React.ErrorInfo | null;
}
const sliceErrorStack = (stackTrace = '', numLines = 10) => {
const lines = stackTrace.split('\n');
const firstNLines = lines.slice(0, numLines);
const joinedLines = firstNLines.join('\n');
return joinedLines;
};
export const AppErrorFallback = ({ error, errorInfo, resetErrorBoundary }: AEFProps) => {
return (
<Jumbotron>
<Alert variant="danger">
<h2>An Error Occurred</h2>
<p>
The application detected an error, and it's been reported to the application development team. You can try clicking
"Reload the Page" to return to the page you were on previously.
</p>
<p>
If the error keeps occurring, please file a bug report with the following details, and include any steps to reproduce the issue:
</p>
<Button onClick={resetErrorBoundary}>Reload the Page</Button>
<h3>Error Details</h3>
<h5>Message</h5>
<pre>{error.message}</pre>
<details>
<summary>Expand to Show Error Stack Traces</summary>
<h5>Stack Trace</h5>
<pre>{sliceErrorStack(error.stack)}</pre>
<h4>Component Stack</h4>
<pre>{sliceErrorStack(errorInfo?.componentStack)}</pre>
</details>
</Alert>
</Jumbotron>
);
};
@usuarez
Copy link

usuarez commented Oct 19, 2022

Hello i try this but next is not rendering the AppErrorFallback.tsx, i'm using react-error-boundary too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment