The issue I am having is that errors thrown in promises are not caught in an error boundary component.
The code fetches data from the server and uses the status code to determine what to do with the data from the response. axios is used as the client and an interceptor is set up to handle the responses.
API.interceptors.response.use((response) => {
switch (response.status) {
case 500:
case 403:
throw new Promise((resolve) => resolve(response.status));
}
});
I have set up an ErrorBoundary component to catch errors thrown in its child components:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
hasError: false,
};
}
componentDidCatch(error) {
this.setState({
hasError: true,
});
if (error instanceof Promise) {
error.then(() => console.log(error));
} else {
console.log(error);
}
}
render() {
return this.state.hasError ? (
<span>Something went wrong but it is okay</span>
) : (
this.props.children
);
}
}
It is used as:
<ErrorBoundary>
<Child />
</ErrorBoundary>
The Child component fetches some data from the server in the componentDidMount method.
componentDidMount() {
API.getData().then((data) => {
...
});
}
When the server responds with a status code that causes the Promise to be thrown, the ErrorBoundary component should catch it but it doesn't. If an error is explicitly thrown inside the componentDidMount method, then the error boundary reacts accordingly. For example:
componentDidMount() {
throw new Error();
// or throw new Promise(resolve => resolve());
}
The error can always be caught with catch but is there a way to have these errors be caught by the ErrorBoundary component?