Skip to content

Commit

Permalink
feat(error-boundary): add handling for any typed values
Browse files Browse the repository at this point in the history
  • Loading branch information
= committed Jan 23, 2025
1 parent 8f2a279 commit 1d68781
Showing 1 changed file with 29 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class Boundary extends Component<BoundaryProps, BoundaryState> {
return {...prevState, error: null, hasError: false, errorInfo: null, watchFor: nextProps.watchFor};
}

componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
private componentDidCatchErrorInstance(error: Error, errorInfo: ErrorInfo): void {
this.setState({hasError: true, error, errorInfo});

const timestamp = new Date().toTimeString();
Expand All @@ -54,12 +54,39 @@ export class Boundary extends Component<BoundaryProps, BoundaryState> {
Boundary.messageStyle,
Boundary.timestampStyle
);

console.error(error);
console.error('Component stack: ', errorInfo.componentStack);
console.groupEnd();
}

private componentDidCatchSomethingWeird(notAnError: unknown, errorInfo: ErrorInfo): void {
this.setState({hasError: true, error: new Error(`Unknown error, based on ${typeof notAnError} value provided.\nReceived value: ${notAnError}, which is not an Error instance.\nTry check your code for throwing ${typeof notAnError}s.`), errorInfo});

const timestamp = new Date().toTimeString();

console.groupCollapsed(
`%cError boundary catched ${typeof notAnError} instead of Error class instance. Try check your code for throwing ${typeof notAnError}s. See details below:` + '%c @ ' + timestamp,
Boundary.messageStyle,
Boundary.timestampStyle
);

console.log(`Received ${typeof notAnError} value: `, notAnError);
console.error('Component stack: ', errorInfo.componentStack);
console.groupEnd();
}

/**
* @param _error - The value throwed from the child component. This is not necessarily an Error class instance because of the ability to throw anything in JS.
* @param errorInfo - React specific object, contains useful componentStack parameter.
*/
componentDidCatch(error: unknown, errorInfo: ErrorInfo): void {
if (error instanceof Error) {
return this.componentDidCatchErrorInstance(error, errorInfo);
}

return this.componentDidCatchSomethingWeird(error, errorInfo);
}

render(): ReactNode {
if (this.state.hasError) {
return (
Expand Down

0 comments on commit 1d68781

Please sign in to comment.