err-reporter.js 1.39 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: encodeURIComponent(location.href),
            u: reporter.getUid(),
            ud: reporter.getUdid(),
            rid: reporter.getReqId(),
            st: JSON.stringify(error && error.stack),
            r: reporter.getRoute()
        });

        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() {
        var self = this;

        window.onerror = function(msg, source, lineno, colno, error) {
            self.writeError(msg, source, lineno, colno, error);
        };

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

module.exports = errReporter;