Skip to content

Commit 238357f

Browse files
committed
feat(react): Add error boundary HOC
1 parent 31d4cf5 commit 238357f

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

packages/react/src/errorboundary.tsx

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import * as Sentry from '@sentry/browser';
2+
import * as hoistNonReactStatic from 'hoist-non-react-statics';
23
import * as React from 'react';
34

45
export const FALLBACK_ERR_MESSAGE = 'No fallback component has been set';
6+
export const UNKNOWN_COMPONENT = 'unknown';
57

68
export type ErrorBoundaryProps = {
79
showDialog?: boolean;
@@ -84,4 +86,24 @@ class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundarySta
8486
}
8587
}
8688

87-
export { ErrorBoundary };
89+
function withErrorBoundary<P extends object>(
90+
WrappedComponent: React.ComponentType<P>,
91+
errorBoundaryOptions: ErrorBoundaryProps,
92+
): React.FC<P> {
93+
const componentDisplayName = WrappedComponent.displayName || WrappedComponent.name || UNKNOWN_COMPONENT;
94+
95+
const Wrapped: React.FC<P> = (props: P) => (
96+
<ErrorBoundary {...errorBoundaryOptions}>
97+
<WrappedComponent {...props} />
98+
</ErrorBoundary>
99+
);
100+
101+
Wrapped.displayName = `boundary(${componentDisplayName})`;
102+
103+
// Copy over static methods from Wrapped component to Profiler HOC
104+
// See: https://reactjs.org/docs/higher-order-components.html#static-methods-must-be-copied-over
105+
hoistNonReactStatic(Wrapped, WrappedComponent);
106+
return Wrapped;
107+
}
108+
109+
export { ErrorBoundary, withErrorBoundary };

packages/react/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export * from '@sentry/browser';
22

33
export { Profiler, withProfiler } from './profiler';
4+
export { ErrorBoundary, withErrorBoundary } from './errorboundary';

0 commit comments

Comments
 (0)