3

I'm trying to catch errors thrown from ReactDOM.render or ReactDOMServer.renderToString.

I can't use componentDidCatch, because I'm trying to simulate an error thrown in SSR. I know that in SSR rendering there are no lifecycle hooks, so that's why I'm trying also with ReactDOM.render.

Here is an example code

A component throwing an error during render:

import React from 'react';

export class Test extends React.Component<any> {
  public componentDidMount(): void {
    this.setState(() => {
      throw new Error('Error');
    });
  }

  public render() {
    return <div>Hello</div>;
  }
}

And a code that tries to catch the thrown error:

try {
  const rendered = ReactDOM.render(<Test />, document.getElementById('root'));
  console.log(rendered);
} catch (e) {
  console.log(e);
}

The result of this code is console log of the rendered component and not the thrown error.

By the way - the page is not rendered in the browser because of that error, but it still passes the "try" and not caught in the "catch". Why is that?

Is there a way to catch rendering errors programmatically like that?

Thanks.

Guy
  • 1,547
  • 1
  • 18
  • 29

0 Answers0