-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathErrorBoundary.jsx
More file actions
78 lines (69 loc) · 2.18 KB
/
Copy pathErrorBoundary.jsx
File metadata and controls
78 lines (69 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { Component } from 'react';
/**
* @typedef {Object} ErrorBoundaryState
* @property {Error | null} error
*/
const devMode = typeof import.meta !== 'undefined' && import.meta.env?.DEV;
/**
* Top-level error boundary. Renders a friendly card with the error
* message, component stack (in dev), and a reload button whenever a
* descendant throws during render. Mounted once in `src/index.jsx` so a
* crash in any demo page keeps the shell alive.
*
* @extends {Component<{ children?: React.ReactNode }, ErrorBoundaryState>}
*/
export default class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { error: null };
}
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
if (devMode) {
console.error('[ErrorBoundary]', error, info);
}
}
handleReload = () => {
window.location.reload();
};
render() {
if (!this.state.error) return this.props.children;
const message = this.state.error?.message || String(this.state.error);
const stack = this.state.error?.stack;
return (
<div
role="alert"
className="d-flex align-items-center justify-content-center vh-100 p-4 bg-light"
>
<div
className="card shadow-sm"
style={{ maxWidth: 720, width: '100%' }}
>
<div className="card-body p-4">
<h1 className="h4 mb-3 text-danger">Something went wrong</h1>
<p className="mb-3 text-muted">
The page hit an unexpected error. Reloading usually clears it.
If it comes back, please copy the details below into an issue.
</p>
<pre
className="bg-light border rounded p-3 small mb-4"
style={{ whiteSpace: 'pre-wrap', maxHeight: 240, overflow: 'auto' }}
>
{message}
{devMode && stack ? `\n\n${stack}` : null}
</pre>
<button
type="button"
className="btn btn-primary"
onClick={this.handleReload}
>
Reload page
</button>
</div>
</div>
</div>
);
}
}