Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端异常捕获 #93

Open
chenchenyuyu opened this issue May 14, 2019 · 1 comment
Open

前端异常捕获 #93

chenchenyuyu opened this issue May 14, 2019 · 1 comment

Comments

@chenchenyuyu
Copy link
Owner

chenchenyuyu commented May 14, 2019

  1. 全局error捕获:
/**
* @param {String}  msg    错误信息
* @param {String}  url    出错文件
* @param {Number}  line   行号
* @param {Number}  col    列号
* @param {Object}  error  错误详细信息
*/
  startErrorLog = () => {
    window.onerror = (msg, url, line, col, error) => {
      //没有URL不上报!上报也不知道错误
      if (msg != "Script error." && !url){
          return true;
      }
      //采用异步的方式
      //我遇到过在window.onunload进行ajax的堵塞上报
      //由于客户端强制关闭webview导致这次堵塞上报有Network Error
      //我猜测这里window.onerror的执行流在关闭前是必然执行的
      //而离开文章之后的上报对于业务来说是可丢失的
      //所以我把这里的执行流放到异步事件去执行
      //脚本的异常数降低了10倍
      setTimeout(() => {
          var data = {};
          //不一定所有浏览器都支持col参数
          col = col || (window.event && window.event.errorCharacter) || 0;
   
          data.url = url;
          data.line = line;
          data.col = col;
          if (!!error && !!error.stack){
              //如果浏览器有堆栈信息
              //直接使用
              data.msg = error.stack.toString();
          }else if (!!arguments.callee){
              //尝试通过callee拿堆栈信息
              var ext = [];
              var f = arguments.callee.caller, c = 3;
              //这里只拿三层堆栈信息
              while (f && (--c > 0)) {
                 ext.push(f.toString());
                 if (f === f.caller) {
                      break;//如果有环
                 }
                 f = f.caller;
              }
              ext = ext.join(",");
              data.msg = error.stack.toString();
          }
          //把data上报到后台!
          console.log('全局error上报', data);
      }, 0);
   
      return true;
  };

    // 当Promise 被reject并且没有得到处理的时候,会触发unhandledrejection事件
    window.addEventListener('unhandledrejection', (e) => {
      const error = e && e.reason
      const message = error.message || '';
      const stack = error.stack || '';
      // Processing error
      let resourceUrl, col, line;
      let errs = stack.match(/\(.+?\)/)
      if (errs && errs.length) errs = errs[0]
      errs = errs.replace(/\w.+[js|html]/g, $1 => { resourceUrl = $1; return ''; })
      errs = errs.split(':')
      if (errs && errs.length > 1) line = parseInt(errs[1] || 0);
      col = parseInt(errs[2] || 0)
      // let defaults = Object.assign({}, errordefo);
      let defaults = {};
      defaults.msg = message;
      defaults.method = 'GET';
      defaults.t = new Date().getTime();
      defaults.data = {
        resourceUrl: resourceUrl,
        line: col,
        col: line
      };
      console.log('全局unhandledrejection上报', defaults)
    });
  }

  1. React组件内部异常捕获:
    componentDidCatch
import React from 'react';

const WithErrorHandler = (WrappedComponent) => {
  class ErrorHandler extends React.Component {
    constructor() {
      super()
      this.state = {
        hasError: false,
      }
    }

    componentDidCatch(error, info) {
      let { message, stack } = error;

      // Processing error
      let resourceUrl, col, line;
      let errs = stack.match(/\(.+?\)/);
      if (errs && errs.length) errs = errs[0];
      errs = errs.replace(/\w.+js/g, $1 => { resourceUrl = $1; return ''; });
      errs = errs.split(':');
      if (errs && errs.length > 1)
        line = parseInt(errs[1] || 0);
      col = parseInt(errs[2] || 0);

      this.setState({
        hasError: true,
      }, () => {
        console.log('TODO组件渲染异常上报=>', error, info.componentStack);
        window.logger.error({
          action: '组件渲染',
          ErrorMessage: message,
          ErrorLineNo: line,
          ErrorColNo: col,
          ErrorUrl: resourceUrl,
          ErrorStack: info.componentStack
        });
      }
      );
      // errorCallback(error, info, this.props);
    }

    componentWillUnmount() {
      this.setState = (state, callback) => {
        return
      }
    }

    render() {
      console.log('渲染组件props', this.props)
      // if (this.state.hasError) {
      //   // 处理异常上报组件
      //   return <h1>wrong</h1>
      // }
      return <WrappedComponent {...this.props} />
    }
  }
  return ErrorHandler;
}

export default WithErrorHandler;

  1. node中间层收集异常统计(source-map准确定位原始异常位置)
const express = require('express');
const fs = require('fs');
const router = express.Router();
const fetch = require('node-fetch');
const sourceMap = require('source-map');
const path = require('path');
const resolve = file => path.resolve(__dirname, file);

// 定义post接口
router.post('/errorMsg/', function(req, res) {
  let error = req.body; // 获取前端传过来的报错对象
  let url = error.scriptURI; // 压缩文件路径

  if (url) {
    let fileUrl = url.slice(url.indexOf('client/')) + '.map'; // map文件路径

    // 解析sourceMap
    let smc = new sourceMap.SourceMapConsumer(fs.readFileSync(resolve('../' + fileUrl), 'utf8')); // 返回一个promise对象
        
    smc.then(function(result) {
        
    // 解析原始报错数据
    let ret = result.originalPositionFor({
      line: error.lineNo, // 压缩后的行号
      column: error.columnNo // 压缩后的列号
    });
            
    let url = ''; // 上报地址
        
    // 将异常上报至后台
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
          errorMessage: error.errorMessage, // 报错信息
          source: ret.source, // 报错文件路径
          line: ret.line, // 报错文件行号
          column: ret.column, // 报错文件列号
          stack: error.stack // 报错堆栈
        })
      }).then(function(response) {
        return response.json();
      }).then(function(json) {
        res.json(json);         
      });
    })
  }
});

module.exports = router;

@chenchenyuyu
Copy link
Owner Author

chenchenyuyu commented May 17, 2019

// window.addEventListener('error', (e) => {
  //   let defaults = {};
  //   defaults.msg = e.target.localName + ' is load error';
  //   defaults.method = 'GET'
  //   defaults.data = {
  //     target: e.target.localName,
  //     type: e.type,
  //     resourceUrl: e.target.href || e.target.currentSrc,
  //   };
  //   if (e.target != window) {
  //     // 没有执行
  //     window.logger.error({ action: 'global error', msg: defaults.msg });
  //   }
  //   console.log('TODO1全局error上报=>', defaults);
  // }, true);

  window.addEventListener('error', (e) => {
    // 资源异常报错上传
    let { error } = e;
    // XXX Ignore errors that will be processed by componentDidCatch.
    // SEE: https://github.com/facebook/react/issues/10474
    if (error.stack && error.stack.indexOf('invokeGuardedCallbackDev') >= 0) {
      return true;
    }
    // Original event handler here...
    let defaults = {};
    defaults.msg = e.target.localName + ' is load error';
    defaults.method = 'GET'
    defaults.resourceUrl = e.target.href || e.target.currentSrc;
    defaults.targetDOMPath = e.target.localName;

    if (e.target != window) {
      // 没有执行
      window.logger.error({ action: 'global error', msg: defaults.msg });
    }
    console.log('TODO1全局error上报=>', defaults);
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant