ntfy/web/src/components/ErrorBoundary.js

81 lines
3.0 KiB
JavaScript
Raw Normal View History

import * as React from "react";
2022-03-10 21:37:50 +01:00
import StackTrace from "stacktrace-js";
2022-04-08 16:44:35 +02:00
import {CircularProgress, Link} from "@mui/material";
2022-03-10 21:37:50 +01:00
import Button from "@mui/material/Button";
2022-04-08 16:44:35 +02:00
import {Trans, withTranslation} from "react-i18next";
2022-04-08 16:44:35 +02:00
class ErrorBoundaryImpl extends React.Component {
constructor(props) {
super(props);
this.state = {
error: false,
originalStack: null,
niceStack: null
};
}
componentDidCatch(error, info) {
2022-03-10 21:37:50 +01:00
console.error("[ErrorBoundary] Error caught", error, info);
// Immediately render original stack trace
const prettierOriginalStack = info.componentStack
.trim()
.split("\n")
.map(line => ` at ${line}`)
.join("\n");
this.setState({
error: true,
originalStack: `${error.toString()}\n${prettierOriginalStack}`
});
// Fetch additional info and a better stack trace
2022-03-10 21:37:50 +01:00
StackTrace.fromError(error).then(stack => {
console.error("[ErrorBoundary] Stacktrace fetched", stack);
const niceStack = `${error.toString()}\n` + stack.map( el => ` at ${el.functionName} (${el.fileName}:${el.columnNumber}:${el.lineNumber})`).join("\n");
this.setState({ niceStack });
2022-03-10 21:37:50 +01:00
});
}
2022-03-10 21:37:50 +01:00
copyStack() {
let stack = "";
if (this.state.niceStack) {
stack += `${this.state.niceStack}\n\n`;
2022-03-10 21:37:50 +01:00
}
stack += `${this.state.originalStack}\n`;
2022-03-10 21:37:50 +01:00
navigator.clipboard.writeText(stack);
}
render() {
2022-04-08 16:44:35 +02:00
const { t } = this.props;
if (this.state.error) {
return (
2022-03-10 21:37:50 +01:00
<div style={{margin: '20px'}}>
2022-04-08 16:44:35 +02:00
<h2>{t("error_boundary_title")} 😮</h2>
2022-03-10 21:37:50 +01:00
<p>
2022-04-08 16:44:35 +02:00
<Trans
i18nKey="error_boundary_description"
components={{
githubLink: <Link href="https://github.com/binwiederhier/ntfy/issues"/>,
discordLink: <Link href="https://discord.gg/cT7ECsZj9w"/>,
matrixLink: <Link href="https://matrix.to/#/#ntfy:matrix.org"/>
}}
/>
2022-03-10 21:37:50 +01:00
</p>
<p>
2022-04-08 16:44:35 +02:00
<Button variant="outlined" onClick={() => this.copyStack()}>{t("error_boundary_button_copy_stack_trace")}</Button>
2022-03-10 21:37:50 +01:00
</p>
2022-04-08 16:44:35 +02:00
<h3>{t("error_boundary_stack_trace")}</h3>
{this.state.niceStack
? <pre>{this.state.niceStack}</pre>
2022-04-08 16:44:35 +02:00
: <><CircularProgress size="20px" sx={{verticalAlign: "text-bottom"}}/> {t("error_boundary_gathering_info")}</>}
<pre>{this.state.originalStack}</pre>
</div>
);
}
return this.props.children;
}
}
2022-04-08 16:44:35 +02:00
const ErrorBoundary = withTranslation()(ErrorBoundaryImpl); // Adds props.t
export default ErrorBoundary;