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. E.g., 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.
CustomError? Does it just extend theErrorclass? For example,class CustomError extends Error?