I am using Sitecore 10.3.1
with JSS-Next.js app version 21.5.3
and Node version 21.7.3
.
My requirement is to handle client and server errors
at the component level. I am currently using the "?" operator to check for null exceptions, but I need a way to handle other exceptions and display a custom error message within the component.
Here is My code files
/Components/Error.tsx
import React, { ReactNode } from 'react';
interface ErrorBoundaryProps { children: ReactNode; }
interface ErrorBoundaryState { hasError: boolean; }
class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> { constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false }; }
static getDerivedStateFromError(): ErrorBoundaryState {
// Update state so the next render will show the fallback UI.
return { hasError: true }; }
componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
// You can also log the error to an error reporting service
console.error('ErrorBoundary caught an error', error, errorInfo); }
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children; } }
export default ErrorBoundary;
Pages/_app.tsx
import type { AppProps } from 'next/app';
import { I18nProvider } from 'next-localization';
import { SitecorePageProps } from 'lib/page-props';
import ErrorBoundary from '../components/Error';
import 'bootstrap/dist/css/bootstrap.css';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
import 'assets/scss/main.scss';
function App({ Component, pageProps }: AppProps<SitecorePageProps>): JSX.Element {
const { dictionary, ...rest } = pageProps;
return (
// Use the next-localization (w/ rosetta) library to provide our translation dictionary to the app.
// Note Next.js does not (currently) provide anything for translation, only i18n routing.
// If your app is not multilingual, next-localization and references to it can be removed.
<I18nProvider lngDict={dictionary} locale={pageProps.locale}>
<ErrorBoundary>
<Component {...rest} />
</ErrorBoundary>
</I18nProvider>
);
}
export default App;
BugComponent.tsx
const BuggyComponent = ({ fields }: HomepageHeroBannerProps): JSX.Element => {
throw new Error('I crashed!');
console.log(fields);
return <div>This will not render</div>;
};
export default withDatasourceCheck()<HomepageHeroBannerProps>(BuggyComponent);
Output
ErrorMsg
1 of 1 unhandled error
Server Error
Error: I crashed!
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
A rendering error occurred: Erroed in Login.
" (yes, "Erroed" is exactly what appeared in the screenshot)