Created
July 18, 2022 12:56
-
-
Save gon250/ba13f83474004ed3d7ad4fb320bd92f3 to your computer and use it in GitHub Desktop.
[Nextjs] ErrorBoundary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class CustomError extends Error { | |
constructor(msg: string) { | |
super(msg); | |
// Set the prototype explicitly. | |
Object.setPrototypeOf(this, CustomError.prototype); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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