Can I Replace Error Boundary With Try Catch Block

By the time with the ReactJs we developed a lot of things and end up with some error. At that point we integrate Error Boundary with react Application. And started to think can I replace error boundary with the Try catch block of vanilla JavaScript ?

The simple answer for the Question for Can I Replace Error Boundary with Try Catch Block : NO

But why I can not replace error boundary with Try catch block ?

In order to understand this we have to look into the mock implementation of the ReactJS and then we would be able to know why we can’t use the Try Catch block.

function ReactComponent() {
  return {
    nodeType: "div",
    nodeText: "Parent",
    child: ReactChildComponent
  };
}

function ReactChildComponent() {
  throw Error("Error");
  return { node: "span", nodeText: "Child" };
}

function ErrorBoundary() {
  return {
    nodeType: "div",
    nodeText: "Error occured in one of the component"
  };
}

function React() {
  this.render = function (Component, ErrorBoundary) {
    let html = ``;

    try {
      const nodesToRender = Component();
      html = `<${nodesToRender.nodeType}> ${nodesToRender.nodeText}`;

      if (nodesToRender.child) {
        const childNodes = nodesToRender.child();
        html =
          html +
          `<${childNodes.nodeType}> ${childNodes.nodeText} </${childNodes.nodeType}> `;

        html = html + `</${nodesToRender.nodeType}>`;
      }
    } catch (error) {
      const nodesToRender = ErrorBoundary();
      html = `<${nodesToRender.nodeType}> ${nodesToRender.nodeText} </${nodesToRender.nodeType}>`;
    }

    document.getElementById("app").innerHTML = html;
  };
}

document.getElementById("app").innerHTML = `
<h1>Error Boundary Replacement With Try Catch </h1>
`;
 new React().render(ReactComponent, ErrorBoundary);

For the Demo i have created the React class/function with render method and created almost similar components and ErrorBoundary component to check why we can not use try catch block in place of Error Boundary.

In this demo we are passing Component as a Callback almostĀ  similar to how we pass the Component in the ReactJS. And inside the React library, React calls the component to get the rendered output and flush it to the DOM.

In this example we call the component and get the output and if there is any error we call the ErrorBoundary.

So ReactJs call the Components and get the output and if component throw error while rendering manually or By any means Ex.=> Not wrapped with the parent Then React calls the ErrorBoundary component and does not throw any error at any time.

So as react does not throw any error we will not get any error In try catch block so there is no mean to have the try catch.

Below is the working example of the Demo Code.

For How to integrate the Error Boundary you can follow this.

Leave a comment

Your email address will not be published. Required fields are marked *