美文网首页
前端异常监控

前端异常监控

作者: TheoLin | 来源:发表于2018-01-15 10:02 被阅读0次

    实现思路

    前端

    js报错事件监听+上报错误信息

    后端
    1. 提供接口收集报错
    2. 根据前端提供的sourcemap文件解析前端上传报错
    3. 整理存储数据,通过邮箱即时把错误信息发送至前端同事
    利用window.onerror方法
    //如果之前其他代码有绑定onerror,需要替换执行一下,如果没有定义window.error===null。
    var oldError = window.onerror;
    window.onerror = function (msg, fileUrl, lineNo, columnNo, error) {//最后两个参数有些部分浏览器拿不到,依然需要记录
    
        var args = Array.prototype.slice.call(arguments);
        
        if (oldError) {
          oldError.apply(window, args)
        }
      var stack = null;
        if(error && error.stack) stack = error.stack;
        var json = {
            msg: msg || null,
            fileUrl: fileUrl || null,
            lineNo: lineNo || null,
            columnNo: columnNo || null,
            error: stack
        }
        var userAgent = navigator.userAgent;
        if(XMLHttpRequest){
            var xhr = new XMLHttpRequest();
            xhr.open('post', 'urlxxx', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send("message="+JSON.stringify(json)+"&userAgent="+encodeURIComponent(userAgent))
        }
    }
    

    可能存在跨域问题,不同域下的js需要配置script属性 crossorigin="anonymous" 和后端配置 Access-Control-Allow-Origin.

    相关文章

      网友评论

          本文标题:前端异常监控

          本文链接:https://www.haomeiwen.com/subject/lfjroxtx.html