React Error Boundaries not working with React
Asked Answered
T

2

29

This is my Error Boundary file -

class ErrorHandling extends Component {
    state = { hasError: false }

    componentDidCatch() {
        this.setState({ hasError: true })
    }

    render() {
        // debugger
        if (this.state.hasError) {
            return <div>Error in Component</div>
        }
        return this.props.children
    }
}

And the other file is -

import React, { Component } from 'react';

// Intentionally I have added syntax error below 'd'

function Intermediate(props) {
    return <h1>hi</h1>;d
}
export default Intermediate

And in my App.js

<ErrorHandling>
  <Intermediate />
</ErrorHandling>

It is causing the application to break without catching the error. Here is the error is seen on the browser screen

enter image description here

The more detailed version here- https://codepen.io/meghana1991/pen/abojydj?editors=0010

When I use the same code in my local with multiple files as above listed, it doesn't work

Tarweed answered 15/9, 2019 at 10:17 Comment(0)
A
47

You can't catch compile-time errors, the Error Boundaries are for run-time errors within the UI.

Refer to Compile time vs run time errors.

Moreover, you have to use getDerivedStateFromError in order to add additional render on fall back UI:

class ErrorBoundary extends React.Component {
  state = {
    hasError: false,
    error: { message: '', stack: '' },
    info: { componentStack: '' }
  };

  static getDerivedStateFromError = error => {
    return { hasError: true };
  };

  componentDidCatch = (error, info) => {
    this.setState({ error, info });
  };

  render() {
    const { hasError, error, info } = this.state;
    const { children } = this.props;

    return hasError ? <ErrorComponent/> : children;
  }
}

For checking your ErrorBoundary, throw an error from a reachable section in the component tree which is not:

  • Event handlers
  • Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
  • Server side rendering
  • Errors thrown in the error boundary itself (rather than its children)
const ButtonComponent = () => {
  throw Error("error!");
  return <></>;
};

Note: In development env you will always see the error overlay unless you turn it off or close it with the X button.


Full example:

const ErrorComponent = () => {
  return <h1>Something went wrong</h1>;
};

class ErrorBoundary extends React.Component {
  state = {
    hasError: false,
    error: { message: "", stack: "" },
    info: { componentStack: "" }
  };

  static getDerivedStateFromError = error => {
    return { hasError: true };
  };

  componentDidCatch = (error, info) => {
    this.setState({ error, info });
  };

  render() {
    const { hasError, error, info } = this.state;
    console.log(error, info);
    const { children } = this.props;

    return hasError ? <ErrorComponent /> : children;
  }
}

const ButtonComponent = () => {
  throw Error("error!");
  return <></>;
};

const App = () => {
  return (
    <ErrorBoundary>
      <ButtonComponent />
    </ErrorBoundary>
  );
};

Edit Error-Boundary Example

Autorotation answered 15/9, 2019 at 10:21 Comment(16)
Tried this now. But unfortunately not working. I still see the error on my app screen.Tarweed
In development env you will always see the error overlay unless you turn it off or close it with the X button.Autorotation
Also add to your question what you seeing, we can't guessAutorotation
Added. Please checkTarweed
I edited the answer, its compile-time error, your application not even starting you can't catch it dynamicallyAutorotation
codepen.io/meghana1991/pen/abojydj?editors=0010 Here it is working as expected. The same code when used with different file for each component, it breaksTarweed
You got a runtime error, thats not the same, try recreating with files here codesandbox.ioAutorotation
this is not working for me, this button click error throwing method ?? any cluesSweat
@ShamseerAhammed I've added a full example with a sandboxAutorotation
@DennisVash sandbox you provided shows default error view ? nothing from error boundary shows up on button click ?Sweat
@ShamseerAhammed Updated the example, you can't catch errors from event handlers like onClick, thank you for catching it up.Autorotation
@DennisVash Correct, in such case you can use this npm package npmjs.com/package/react-error-boundaryBurletta
thank you you saved a lot of time for me of searching for the issue that the error still appears in the development env. Thank you.Interstadial
Use native API like .catch in promises, depending on your async case.Autorotation
@DennisVash Any idea how to disable error overlays in development? I want to check my fallback UI when there is an errorSheeree
Seems like your example is also working with runtime.Ackerman
D
3

The thing is: the nice fallback UI you can see in the React docs example only appears in production. So you have to run the suggested by create-react-app (id you use it) command:

npm run build
# wait for it to finish
serve -s build

Then open localhost:5000 in your browser (if you see this address in the terminal mentioned). This way the React docs example works fine.

Dumyat answered 8/7, 2021 at 12:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.