如何在生产中测试错误边界?

时间:2019-11-06 16:42:56

标签: reactjs error-handling

我正在向应用程序添加顶级错误边界。本地一切正常,但是我不确定如何在生产中进行测试,因为我不知道任何渲染错误。有没有办法强迫React组件在错误中抛出错误?还是有更好的方法来确保错误边界在没有实际错误的情况下应做的事情?

2 个答案:

答案 0 :(得分:0)

比方说,我有一个Parent组件,它有两个孩子,每个孩子都包裹在ErrorBoundary内。如果任何子代发生任何错误,则ErrorBoundary会自行呈现,而不是出现错误的子代。

Parent.js

<Parent>
  <Child02 />
  <Child01 /> {/*It's a Setting icon, check out the pic below*/}
</Parent>

Child02.js

render(){
return(
<ErrorBoundary>
  <div>my custom components value </div>
  <ErrorComponent />
</ErrorBoundary>
);}

ErrorBoundary.js 您可以修改render想要显示给用户的内容...等

import React from "react";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    console.log("my custom error: ", error, errorInfo);

    // logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

ErrorComponent.js 让我们在 ErrorComponent

内抛出错误
export default class ErrorComponent extends Component {
  render() {
    const x = 5;
    x = 7; //it will throw error, because we can't change a constant's value
    return <div>hello  
{/* some dynamic logic..etc which may cause Error in future */}
</div>;
  }
}

this is what my ErrorBoundary renders

由于组件 ErrorComponent 出现错误,因此父级组件将呈现以下内容:

<Parent>
  <Child01 />
  <h1>Something went wrong.</h1> {/*this is what ErrorBoundary renders, it's coming from ErrorBoundary's render method*/}
</Parent>

答案 1 :(得分:0)

要强制触发ErrorBoundary,只需在子组件中引发错误 使用标准的错误抛出:throw new Error("Something went wrong") 如果只想在生产中出现错误,则可以检查“ NODE_ENV”是否设置为“生产”,然后仅抛出错误。