Add ErrorBoundary to page content

Prevent the page from turning into a black screen when page rendering
fails by adding an error boundary to the display of the page content in
SiteLayout.jsx.
This commit is contained in:
Hornwitser committed 2021-02-24 19:48:43 +01:00
1 parent ac17b8497a
commit b538960592
4 files changed
+50 -1

No files matched your search

@@ -0,0 +1,20 @@
import React from "react";
export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null };
}
static getDerivedStateFromError(error) {
return { error };
}
render() {
if (this.state.error) {
return <this.props.Component error={this.state.error} />;
}
return this.props.children;
}
}
@@ -0,0 +1,16 @@
import React, { useContext } from "react";
import { Typography } from "antd";
import libLink from "@clusterio/lib/link";
import PageLayout from "./PageLayout";
const { Paragraph } = Typography;
export default function ErrorPage(props) {
return <PageLayout nav={[{ name: "Error" }]}>
<h2>An unexpected error occured</h2>
<Paragraph code className="error-traceback">{props.error.stack}</Paragraph>
</PageLayout>;
};
@@ -3,6 +3,9 @@ import { Switch, Route, useHistory } from "react-router-dom";
import { Layout, Menu } from "antd";
import webUiPackage from "../../package.json";
import ErrorBoundary from "./ErrorBoundary";
import ErrorPage from "./ErrorPage";
const { Header, Sider } = Layout;
@@ -74,7 +77,9 @@ export default function SiteLayout(props) {
</Route>)}
{pages.map(page => <Route exact path={page.path} key={page.path}>
<SetSidebar path={page.sidebarPath} />
{page.content}
<ErrorBoundary Component={ErrorPage}>
{page.content}
</ErrorBoundary>
</Route>)}
<Route>
<SetSidebar path={null} />
+8
View File
@@ -82,6 +82,14 @@ body {
background-size: 64px;
}
.error-traceback code {
display: block;
margin: 0;
background: #000;
border-color: #252525;
white-space: pre-wrap;
}
.rcon-result code {
display: block;
background: #000;