react umi、umi max 的异常错误捕获

有时候某个js加载失败会导致页面报错,不能正常展示 例如Something went wrong
如图


错误示例

写一个错误捕获的组件

注意:这个组件只有在打包后才生效,本地运行是不能捕获到错误的
import { RedoOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import React, { Component } from 'react';
import './error.less';

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

  componentDidCatch(error, info) {
    // 你可以在这里处理错误信息,例如发送到服务器记录
    console.error('ErrorBoundary caught an error', error, info);
    this.setState({ hasError: true });
  }
  refresh() {
    window.location.reload();
  }

  render() {
    if (this.state.hasError) {
      // 可以在这里渲染一个错误提示
      return (
        <>
          <div className="error-container">
            <h1 className="error-title">页面出现错误</h1>
            <p className="error-message">
              很抱歉,资源加载失败,导致页面无法正常显示。
            </p>
            <div className="error-details">
              <p>描述: 资源加载失败</p>
              <p>
                建议:
                请检查网络状态并刷新重试,如果问题依旧,请联系我们的技术支持。
              </p>
              <p style={{ textAlign: 'center' }}>
                <Button
                  type="primary"
                  className="mr-20"
                  icon={<RedoOutlined />}
                  onClick={this.refresh}
                >
                  刷新重试
                </Button>
              </p>
            </div>
          </div>
        </>
      );
    }
    return this.props.children;
  }
}

export default ErrorBoundary;

error.less文件

.error-container {
  max-width: 600px;
  margin: 50px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 10%);
  margin-top: 216px;

  p {
    padding: 10px;
  }
}

.error-title {
  color: #d9534f;
  font-size: 24px;
  margin-bottom: 10px;
}

.error-message {
  color: #333;
  font-size: 18px;
  margin-bottom: 20px;
}

.error-details {
  color: #777;
  font-size: 14px;
}

在全局组件外面用错误组件包裹住页面


示例
效果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容