Skip to content

Instantly share code, notes, and snippets.

@gon250
Created July 18, 2022 12:56
Show Gist options
  • Save gon250/ba13f83474004ed3d7ad4fb320bd92f3 to your computer and use it in GitHub Desktop.
Save gon250/ba13f83474004ed3d7ad4fb320bd92f3 to your computer and use it in GitHub Desktop.
[Nextjs] ErrorBoundary
import type { AppProps } from "next/app";
import { ToastContainer } from "react-toastify";
import ErrorBoundary from '@components/error/ErrorBoundary';
function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
export default App;
export class CustomError extends Error {
constructor(msg: string) {
super(msg);
// Set the prototype explicitly.
Object.setPrototypeOf(this, CustomError.prototype);
}
}
import React, {Component, ErrorInfo, ReactNode} from 'react';
import {CustomError} from '@components/error/custom.error';
interface Props {
children?: ReactNode;
}
interface State {
hasError: boolean;
errorMessage: string | null;
}
class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false,
errorMessage: null,
};
public static getDerivedStateFromError(error: Error | CustomError): State {
if (error instanceof CustomError) {
return {hasError: true, errorMessage: error.message};
}
return {hasError: true, errorMessage: null};
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Uncaught error:', error, errorInfo);
}
public render() {
if (this.state.hasError) {
return <h1>{this.state.errorMessage ?? 'Sorry.. there was an error'}</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment