简体   繁体   中英

How do I work with custom error types in React error boundaries?

I have an error boundary set at the top of my component tree, like this:

renderApp() {
  return (
    <ErrorBoundary>
      { this.props.children }
    </ErrorBoundary>
  );
}

Should an error find its way up the tree, the error boundary renders a simple error page, passing the error itself as a prop:

componentDidCatch(error, info) {
  this.setState({
    hasError: true,
    error
  });
}

render() {
  if (this.state.hasError) {
    return (
      <ErrorPage error={this.state.error}/>
    );
  }
  return this.props.children;
}

I've started to define custom errors to throw around the application when certain exceptions are raised, simply extending the Error class:

class CustomError extends Error {}

Then in my components, I'm throwing these custom errors, which I'd like to detect in my error page and construct messaging based on their type. Eg, if I'm throwing this error further down in the component tree:

throw new CustomError('This is the custom error message');

I'd like to be able to sniff the type in my error page, and display messaging that's pertinent for that type.

import CustomError from '../../errors/custom-error';

// This code has obviously been edited for brevity's sake

class ErrorPage extends React.Component {
  render() {
    if (this.props.error instanceof CustomError) {
      errorMessage = "A custom error occurred.";
    }
    return <div>{errorMessage}</div>;
  }
}

However, in the error page, React only recognizes that this.props.error is an instanceof Error , not of CustomError . If I throw, say, a TypeError instead of a CustomError , then the error page can detect the error type. But passing the custom error type results in the error page knowing nothing about the type other than that it's an error, which obviously defeats the purpose of defining custom error types. What am I missing here? Is this a bug in React? Any input would be most appreciated.

I discovered this issue using React 16.0.0, have updated to 16.2.0 and the problem persists.

I created a Github repository that shows how React handles error boundaries.

It seems like React is able to detect CustomError . See this line of code here .

Let me know if this example is representative of what you have.

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