Saber2pr's Blog


Error handling in React

  1. Unified capture in workLoop Big Loop
try {
} catch (error) {

function handleError(error) {

Source location Https:// ThrowException is called in handleError, so it mainly depends on the throwException implementation: (simplified, only class and host components are shown)

function throwException(fiber, errorInfo) {
  let workInProgress = fiber
  while (workInProgress) {
    switch (workInProgress.tag) {
      case HostRoot: {
        createRootErrorUpdate(workInProgress, errorInfo)
      case ClassComponent:
        const ctor = workInProgress.type
        const instance = workInProgress.stateNode
        if (
          typeof ctor.getDerivedStateFromError === "function" ||
          typeof instance.componentDidCatch === "function"
        ) {
          createClassErrorUpdate(workInProgress, errorInfo)
    workInProgress = workInProgress.return

The principle is to use the fiber.return linked list to find out whether the parent class component implements the componentDidCatch method. The logError method is called internally in createClassErrorUpdate to print the component tree, which is still fiber.return up and collects the displayName of the component. About the hook component is to find the parent Suspense fallback for error rollback.