Errorable.tsx
1 import React from 'react'; 2 import { connect } from 'react-redux'; 3 4 import { notificationsActions } from 'features/notifications'; 5 6 interface DispatchProps { 7 showNotification: notificationsActions.TShowNotification; 8 } 9 10 interface OwnProps { 11 /** 12 * Optional custom error message to display when a error is caught, otherwise the 13 * actual error message is displayed to the user 14 */ 15 errorMessage?: string; 16 /** 17 * Optional should catch condition, if left undefined then the component will by default 18 * catch all errors, if false, then the component will not catch errors, if true, 19 * the component will catch errors 20 */ 21 shouldCatch?: boolean; 22 23 /** 24 * Optional callback handler when an error is encountered and this component 25 * should catch it 26 */ 27 onError?(): void; 28 } 29 30 type Props = DispatchProps & OwnProps; 31 32 class ErrorBoundary extends React.Component<Props> { 33 public componentDidCatch(error: Error, info: any) { 34 console.error(error); 35 console.error(info); 36 const { errorMessage, onError, shouldCatch } = this.props; 37 38 if (shouldCatch === false) { 39 throw error; 40 } 41 42 this.props.showNotification('danger', errorMessage || error.message); 43 if (onError) { 44 onError(); 45 } 46 } 47 48 public render() { 49 return this.props.children; 50 } 51 } 52 53 export default connect(null, { showNotification: notificationsActions.showNotification })( 54 ErrorBoundary 55 );