feat(ErrorBoundary): ✨ add ReactBasicErrorBoundary and ReactErrorBoundary components
* Implemented ReactBasicErrorBoundary for error handling. * Created ReactErrorBoundary with enhanced error reporting features. * Updated index file to export both components.
This commit is contained in:
70
src/ErrorBoundary/BasicErrorBoundary.tsx
Normal file
70
src/ErrorBoundary/BasicErrorBoundary.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import React, { type PropsWithChildren } from 'react';
|
||||
|
||||
interface ErrorBoundaryProps extends PropsWithChildren {
|
||||
namespace?: string;
|
||||
onReportClick?: () => void;
|
||||
onResetClick?: () => void;
|
||||
onRetryClick?: () => void;
|
||||
reportAPI?: string;
|
||||
}
|
||||
|
||||
interface ErrorBoundaryState {
|
||||
error: any;
|
||||
errorInfo: any;
|
||||
reported?: boolean;
|
||||
resetted?: boolean;
|
||||
showDetail: boolean;
|
||||
timer?: NodeJS.Timeout | undefined;
|
||||
try: boolean;
|
||||
tryCnt: number;
|
||||
}
|
||||
|
||||
export class ReactBasicErrorBoundary extends React.PureComponent<
|
||||
ErrorBoundaryProps,
|
||||
ErrorBoundaryState
|
||||
> {
|
||||
constructor(props: ErrorBoundaryProps) {
|
||||
super(props);
|
||||
|
||||
this.state = {
|
||||
error: null,
|
||||
errorInfo: null,
|
||||
showDetail: false,
|
||||
timer: undefined,
|
||||
try: false,
|
||||
tryCnt: 0,
|
||||
};
|
||||
}
|
||||
|
||||
componentDidCatch(error: any, errorInfo: any) {
|
||||
// Catch errors in any components below and re-render with error message
|
||||
this.setState({
|
||||
error,
|
||||
errorInfo,
|
||||
try: false,
|
||||
});
|
||||
// You can also log error messages to an error reporting service here
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.errorInfo) {
|
||||
// Error path
|
||||
return (
|
||||
<div>
|
||||
<h2>Error</h2>
|
||||
{this.state.error && (
|
||||
<>
|
||||
<h3>In: {this.props.namespace ?? 'default'}</h3>
|
||||
<main>{this.state.error.toString()}</main>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Normally, just render children
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
export default ReactBasicErrorBoundary;
|
||||
Reference in New Issue
Block a user