2024-06-03 20:35:06 +02:00
|
|
|
// Copyright 2024, Command Line Inc.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
import React, { ReactNode } from "react";
|
|
|
|
|
2024-09-10 03:19:41 +02:00
|
|
|
export class ErrorBoundary extends React.Component<
|
|
|
|
{ children: ReactNode; fallback?: React.ReactElement & { error?: Error } },
|
|
|
|
{ error: Error }
|
|
|
|
> {
|
2024-06-03 20:35:06 +02:00
|
|
|
constructor(props) {
|
|
|
|
super(props);
|
|
|
|
this.state = { error: null };
|
|
|
|
}
|
|
|
|
|
|
|
|
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
|
|
|
|
this.setState({ error: error });
|
|
|
|
}
|
|
|
|
|
|
|
|
render() {
|
2024-09-10 03:19:41 +02:00
|
|
|
const { fallback } = this.props;
|
2024-06-03 20:35:06 +02:00
|
|
|
const { error } = this.state;
|
|
|
|
if (error) {
|
2024-09-10 03:19:41 +02:00
|
|
|
if (fallback != null) {
|
|
|
|
return React.cloneElement(fallback as any, { error });
|
|
|
|
}
|
2024-06-03 20:35:06 +02:00
|
|
|
const errorMsg = `Error: ${error?.message}\n\n${error?.stack}`;
|
|
|
|
return <pre className="error-boundary">{errorMsg}</pre>;
|
|
|
|
} else {
|
|
|
|
return <>{this.props.children}</>;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|