How to use reactErrorHandler
in a shared-environment(multiple scope client)
#13082
-
I'm developing a Chrome Extension using React and following best practices by setting up multiple scoped clients. I want to use these Utils in React(e.g. |
Beta Was this translation helpful? Give feedback.
Answered by
AbhiPrasad
Jul 30, 2024
Replies: 1 comment 3 replies
-
@1natsu172 I recommend just vendoring in the code and then adding an explicit call to /**
* Recurse through `error.cause` chain to set cause on an error.
*/
export function setCause(error: Error & { cause?: Error }, cause: Error): void {
const seenErrors = new WeakSet();
function recurse(error: Error & { cause?: Error }, cause: Error): void {
// If we've already seen the error, there is a recursive loop somewhere in the error's
// cause chain. Let's just bail out then to prevent a stack overflow.
if (seenErrors.has(error)) {
return;
}
if (error.cause) {
seenErrors.add(error);
return recurse(error.cause, cause);
}
error.cause = cause;
}
recurse(error, cause);
}
/**
* Captures an error that was thrown by a React ErrorBoundary or React root.
*
* @param error The error to capture.
* @param errorInfo The errorInfo provided by React.
* @param hint Optional additional data to attach to the Sentry event.
* @returns the id of the captured Sentry event.
*/
export function captureReactException(
scope: Scope,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error: any,
{ componentStack }: ErrorInfo,
hint?: EventHint,
): string {
// Create stack trace from componentStack param and links
// to to the original error using `error.cause` otherwise relies on error param for stacktrace.
// Linking errors requires the `LinkedErrors` integration be enabled.
// See: https://reactjs.org/blog/2020/08/10/react-v17-rc.html#native-component-stacks
//
// Although `componentDidCatch` is typed to accept an `Error` object, it can also be invoked
// with non-error objects. This is why we need to check if the error is an error-like object.
// See: https://github.com/getsentry/sentry-javascript/issues/6167
if (isError(error) && componentStack) {
const errorBoundaryError = new Error(error.message);
errorBoundaryError.name = `React ErrorBoundary ${error.name}`;
errorBoundaryError.stack = componentStack;
// Using the `LinkedErrors` integration to link the errors together.
setCause(error, errorBoundaryError);
}
return scope.captureException(error, {
...hint,
captureContext: {
contexts: { react: { componentStack } },
},
});
} |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
1natsu172
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@1natsu172 I recommend just vendoring in the code and then adding an explicit call to
scope.X