简体   繁体   中英

Catching a warning with Error Boundary (React)

Noob here, not too sure about component configuration, so I ended up with an routing warning error (ie "No routes matched location "/play") which is displayed as a warning.

I'm tying to convert this into an error, and then hand it over to ErrorBoundary. It gets converted, but it's not being caught, so ErrorBoundary doesn't activate. What am I doing wrong?

//coverting the warning --No routes matched location "/play"-- into an error
console.warn = function (...args) {
  setTimeout(() => {
    throw new Error(args[0]);
  }, 0);
};

class ErrorBoundary extends Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    console.error("Error boundary caugh an error", error, info);
  }

Convert a warning into an error and handle it with ErrorBoundary

According to react documents

Error boundaries do not catch errors for asynchronous code (eg setTimeout or requestAnimationFrame callbacks).

Asynchronous errors can be handled using unhandledrejection event.

import { useEffect } from "react";

export default function ErrorBoundary({ children }) {
  const captureReject = (e) => {
    e.preventDefault();
    console.log(error);
  };

  useEffect(() => {
    window.addEventListener('unhandledrejection', captureReject);
    return () => {
      window.removeEventListener('unhandledrejection', captureReject);
    }
  }, []);

  return children;
}

You can use it like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM