better FE error handling
This commit is contained in:
1 parent
b329e3f594
commit
9e9cea9269
5 files changed
+106
-10
No files matched your search
@@ -0,0 +1,7 @@
|
||||
.error-boundary {
|
||||
padding: 2em 5%;
|
||||
}
|
||||
|
||||
h1, h2 {
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import React, { FC } from "react";
|
||||
import { ComponentMeta, ComponentStory } from '@storybook/react';
|
||||
import { ErrorBoundary } from ".";
|
||||
|
||||
|
||||
export default {
|
||||
title: 'ErrorBoundary',
|
||||
component: ErrorBoundary,
|
||||
parameters: { actions: { argTypesRegex: '^on.*' } },
|
||||
args: {
|
||||
}
|
||||
} as ComponentMeta<typeof ErrorBoundary>
|
||||
|
||||
export const ErrorThrown: ComponentStory<typeof ErrorBoundary> = args => {
|
||||
const BadComponent: FC = () => {
|
||||
throw new Error("!!!")
|
||||
}
|
||||
return <div className="page">
|
||||
<ErrorBoundary>
|
||||
<BadComponent />
|
||||
</ErrorBoundary>
|
||||
</div>
|
||||
}
|
||||
|
||||
export const NoError: ComponentStory<typeof ErrorBoundary> = args => {
|
||||
const GoodComponent: FC = () => {
|
||||
return <span>All Good.</span>
|
||||
}
|
||||
return <div className="page">
|
||||
<ErrorBoundary>
|
||||
<GoodComponent />
|
||||
</ErrorBoundary>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import "./index.css";
|
||||
import { Component, ErrorInfo } from "react";
|
||||
|
||||
type State = {
|
||||
hasError: false;
|
||||
} | {
|
||||
hasError: true,
|
||||
error: any,
|
||||
errorInfo?: ErrorInfo,
|
||||
}
|
||||
export class ErrorBoundary extends Component<{}, State> {
|
||||
|
||||
state: State = {
|
||||
hasError: false
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: any): State {
|
||||
return { error, hasError: true, };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
||||
this.setState({
|
||||
hasError: true,
|
||||
error,
|
||||
errorInfo,
|
||||
})
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
return <div className="error-boundary">
|
||||
<h1>An Error has occured.</h1>
|
||||
<h2>{String(this.state.error)}</h2>
|
||||
{JSON.stringify(this.state.error, null, 4)}
|
||||
<br />
|
||||
{this.state.errorInfo && this.state.errorInfo.componentStack.split('\n').map((s, i) => <>
|
||||
<span key={i}>{s}</span><br key={`br-${i}`} />
|
||||
</>)}
|
||||
</div>
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user