How to prevent triggering the error event on window when error is caught by error boundary?

39 views Asked by At

Is there a way to prevent triggering the error event on the window when the React error boundary catches the error?

By now, the error is caught by the error boundary and error event on the window.

In other words, when an error is caught by the error boundary, the error handling code in window.onerror should not be executed.

App.tsx:

import "./styles.css";
import ErrorBoundary from "./ErrorBoundary";
import { useEffect, useState } from "react";

const ErrorComponent = () => {
  const [showError, setShowError] = useState(false);
  useEffect(() => {
    if (showError) JSON.parse("");
  }, [showError]);

  return (
    <button
      onClick={() => {
        setShowError(true);
      }}
    >
      JSON parse SyntaxError
    </button>
  );
};

export default function App() {
  useEffect(() => {
    const handleError = () => {
      console.log("Please contact the sale. 888-888-888");
    };

    window.addEventListener("error", handleError);
    return () => {
      window.removeEventListener("error", handleError);
    };
  }, []);

  return (
    <ErrorBoundary>
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <ErrorComponent />
      </div>
    </ErrorBoundary>
  );
}

ErrorBoundary.tsx:

import React from "react";

class ErrorBoundary extends React.Component {
  public static getDerivedStateFromError(error: any) {
    return { hasError: true };
  }

  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  public render() {
    const { hasError } = this.state;
    console.log("hasError: ", hasError);
    if (hasError) {
      return <div>Something went wrong</div>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

codesandbox

0

There are 0 answers