badjs.js 1.24 KB
var cookies = require('../cookie');
var reporter = require('./reporter');

var errorKey = '_errLog';

var errReporter = {
    writeError: function(msg, source, lineno, colno, error) {
        var errorList = JSON.parse(cookies(errorKey) || '[]');

        errorList.push({
            tp: 'err',
            msg: msg,
            sc: source,
            ln: lineno,
            cn: colno,
            pt: location.href,
            u: reporter.getUid(),
            ud: reporter.getUdid(),
            rid: reporter.getReqId(),
            st: JSON.stringify(error && error.stack)
        });

        cookies(errorKey, JSON.stringify(errorList));

        if (errorList.length >= 5) {
            this.reportError();
        }
    },
    clearError: function() {
        cookies(errorKey, '[]');
    },
    reportError: function() {
        var self = this;
        var errorList = JSON.parse(cookies(errorKey) || '[]');
        var errStr = reporter.stringify(errorList);

        reporter.report(errStr, function() {
            self.clearError();
        });
    },
    init: function() {
        window.onerror = this.writeError.bind(this);

        // 上报未上报的事件
        this.reportError();
    }
};

errReporter.init();

module.exports = errReporter;