Skip to content

Instantly share code, notes, and snippets.

@jdelStrother
Created January 26, 2023 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdelStrother/431d60131eaa09cdb62b1215ac07ad00 to your computer and use it in GitHub Desktop.
Save jdelStrother/431d60131eaa09cdb62b1215ac07ad00 to your computer and use it in GitHub Desktop.
// This prevents error propagation, so that Storybook doesn't show its onerror report,
// and the browser (or jest) doesn't display console.error messages
const SilenceConsole = (props: { children: JSX.Element }) => {
const [ready, setReady] = React.useState(false);
React.useLayoutEffect(() => {
function handler(e: ErrorEvent) {
// prevent React's listener from firing
e.stopImmediatePropagation();
// prevent the browser's console error message
e.preventDefault();
}
window.addEventListener("error", handler, true);
// Sadly react still insists on logging the error, haven't found a way of
// suppressing that without resorting to overriding console.error()
const originalConsoleError = console.error;
console.error = () => {};
setReady(true);
return () => {
console.error = originalConsoleError;
window.removeEventListener("error", handler, true);
};
}, []);
return ready ? props.children : null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment