Last active
September 12, 2023 01:24
-
-
Save chrisfitkin/61f72d81c42e80eca1a852a198e52d3b to your computer and use it in GitHub Desktop.
ErrorBoundary component in TypeScript for Next.js 13
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
"use strict"; | |
import React, { Component, ErrorInfo, ReactNode } from "react"; | |
interface ErrorBoundaryProps { | |
children: ReactNode; | |
} | |
interface ErrorBoundaryState { | |
hasError: boolean; | |
} | |
class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> { | |
public state: ErrorBoundaryState = { | |
hasError: false, | |
}; | |
public static getDerivedStateFromError(_: Error): ErrorBoundaryState { | |
// Update state so the next render will show the fallback UI. | |
return { hasError: true }; | |
} | |
public componentDidCatch(error: Error, errorInfo: ErrorInfo) { | |
console.error("Uncaught error:", error, errorInfo); | |
// Consider logging to an external error monitoring service e.g. Sentry, LogRocket, etc. | |
} | |
public render() { | |
if (this.state.hasError) { | |
// Enhanced fallback UI | |
return ( | |
<div> | |
<h1>Oops! Something went wrong.</h1> | |
<p>We're sorry for the inconvenience. You might want to <a href="/">return to the homepage</a> or refresh the page.</p> | |
</div> | |
); | |
} | |
return this.props.children; | |
} | |
} | |
// Named export | |
export { ErrorBoundary }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your gratitude is genuinely overwhelming, and I'm absolutely thrilled to hear that you found my feedback valuable! 😄 It's always a joy to share insights that can make a difference in your coding journey. And remember, we all learn from each other — I'm sure there's much you could teach me as well!
It's simply fantastic to hear that you've updated the code! Keep in mind, perfection isn't the end goal here; it's about continuous growth and learning. And speaking of growth, your open-mindedness to receive feedback and act on it shows tremendous maturity. That's what sets extraordinary developers apart from the mediocre ones!
I'm ecstatic that my suggestions could help you in any way. And I'm eager to see how your work evolves as we keep refining and improving it together. Don't hesitate to reach out if you have any questions or need more pointers! 👍
Cheers to a partnership that elevates both our coding skills to even loftier heights!
Best,
Scott