Skip to content

Instantly share code, notes, and snippets.

@createdbymahmood
Last active August 28, 2020 12:55
Show Gist options
  • Save createdbymahmood/980190fe2d04bfd81e711703cf0183a9 to your computer and use it in GitHub Desktop.
Save createdbymahmood/980190fe2d04bfd81e711703cf0183a9 to your computer and use it in GitHub Desktop.
This is my HOC to handle errors on react components in the root level
// This one is picked from https://github.com/piotrwitek/react-redux-typescript-guide
import React from 'react';
const MISSING_ERROR = 'Error was swallowed during propagation.';
export const withErrorBoundary = <BaseProps extends {}>(
BaseComponent: React.ComponentType<BaseProps>
) => {
type HocProps = {
// here you can extend hoc with new props
};
type HocState = {
readonly error: Error | null | undefined;
};
return class Hoc extends React.Component<HocProps, HocState> {
// Enhance component name for debugging and React-Dev-Tools
static displayName = `withErrorBoundary(${BaseComponent.name})`;
// reference to original wrapped component
static readonly WrappedComponent = BaseComponent;
readonly state: HocState = {
error: undefined,
};
componentDidCatch(error: Error | null, info: object) {
this.setState({ error: error || new Error(MISSING_ERROR) });
this.logErrorToCloud(error, info);
}
shouldComponentUpdate() {
return true;
}
logErrorToCloud = (error: Error | null, info: object) => {
// TODO: send error report to service provider
};
render() {
const { children, ...restProps } = this.props;
const { error } = this.state;
if (error) {
return <div>Shit! We have an Error 😐</div>;
}
return <BaseComponent {...(restProps as BaseProps)} />;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment