-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathErrorBoundary.tsx
47 lines (38 loc) · 1.2 KB
/
ErrorBoundary.tsx
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
import React, { Component, ReactNode } from 'react';
import { getAppEnv } from './getAppEnv';
type Props = {
children: ReactNode;
};
type State = {
hasError: boolean;
error?: Error;
};
class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error: Error): State {
// Update state so the next render will show the error in development or log in production
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
if (getAppEnv() === 'production') {
// Log the error to an error reporting service in production
console.error('Uncaught error:', error, errorInfo);
}
}
render() {
if (this.state.hasError) {
if (getAppEnv() === 'development') {
// Display the error message on screen in development mode
return <div>An error occurred: {this.state.error?.message}</div>;
} else {
// In production, you might want to render a generic error message
return <div>Something went wrong</div>;
}
}
return this.props.children;
}
}
export default ErrorBoundary;