前端异常捕获

162 阅读1分钟

前端异常捕获的四种方式

使用try catch捕获同步代码或async await报错

window.adEventLisenter('error', () => {})

监听js报错或资源加载报错

window.addEventLisenter('unhandledrejection', () => {})

捕获未被catch的promise报错

app.config.errorHandler = (err, vm, info) => {}

捕获vue框架层面的报错

ComponentDidCatch钩子,react项目的最外层组件添加ComponentDidCatch钩子组件。

class ErrorBoundary extends React.Component {
  componentDidCatch(error, info) {
    // 处理异常
  }
}

<ErrorBoundary>
  <App />
</ErrorBoundary>

捕获react框架层面的报错

上报处理

上报分类

非紧急报错:

  • 所有的报错,存放到队列中。在浏览器空闲时做批量上报。
  • 在浏览器关闭时使用navigator.sendBeacon上报队列中的所有数据

紧急报错:(如页面白屏)

  • 监控方案
  • 1: 监控到报错后,获取root的Dom节点内容,如果不存在则说明页面白屏了
  • 2: react 16后使用getDerivedStateFromError捕获react中所有的渲染异常
class ErrorBoundary extends React.Component { 
    constructor(props) { 
        super(props); 
        this.state = { hasError: false }; 
    } 
    static getDerivedStateFromError(error) { // 更新 state 使下一次渲染能够显示降级后的 UI 
        return { hasError: true }; 
    } 
    componentDidCatch(error, errorInfo) { // 我们可以将错误日志上报给服务器 
        logErrorToMyService(error, errorInfo); 
    } 
    render() { 
        if (this.state.hasError) { // 我们可以自定义降级后的 UI 并渲染 
            return <h1>Something went wrong.</h1>; } 
        return this.props.children; 
    } 
}

紧急报错报错采用同步的方式上报,甚至可以介入邮件,电话预警。

前端异常上报方案二

接入sentry

参考文章:

zh-hans.reactjs.org/docs/error-… www.mk2048.com/blog/blog_h…