«

js实现前端错误自动上报功能

时间:2024-2-21 13:27     作者:韩俊     分类: Javascript


在pc和移动端中在线上发生前端错误难以查看错误,特别是在用户真机移动端中难以定位错误,为了更好解决线上问题,所以需要对前端发生报错信息进行收集上报,然后通过后端的接口传递错误给记录下来。

以下主要分为资源加载错误和运行时错误,监听代码错误然后调用请求上报方法传递错误信息和设备信息:

window.onerror = function (
    errorMessage,
    scriptURI,
    lineNumber,
    columnNumber,
    errorObj
) {
    reportException({
        exceptionmsg: errorMessage,
        appinfo: window.navigator.userAgent,
        phoneinfo:
            document.documentElement.clientWidth +
            "x" +
            document.documentElement.clientHeight,
        deviceinfo: scriptURI + " line:" + lineNumber,
    });
    //无法监听资源加载异常
};

监听资源类错误,上报前过滤掉一些其它错误

window.addEventListener(
    "error",
    function (event) {
        //过滤掉监听的代码逻辑错误
        let target = event.target || event.srcElement;
        let isElementTarget =
            target instanceof HTMLScriptElement ||
            target instanceof HTMLLinkElement ||
            target instanceof HTMLImageElement;
        if (!isElementTarget) return false;
    ...
    },
    true
);

下面是完整的实现代码:

(function collectException() {//前端错误收集上报
    window.addEventListener(
        "error",
        function (event) {
            //过滤掉监听的代码逻辑错误
            let target = event.target || event.srcElement;
            let isElementTarget =
                target instanceof HTMLScriptElement ||
                target instanceof HTMLLinkElement ||
                target instanceof HTMLImageElement;
            if (!isElementTarget) return false;
            reportException({
                exceptionmsg: event.type,
                appinfo: window.navigator.userAgent,
                phoneinfo:
                    document.documentElement.clientWidth +
                    "x" +
                    document.documentElement.clientHeight,
                deviceinfo: event.target.src,
            });
        },
        true
    );
    window.onerror = function (
        errorMessage,
        scriptURI,
        lineNumber,
        columnNumber,
        errorObj
    ) {
        reportException({
            exceptionmsg: errorMessage,
            appinfo: window.navigator.userAgent,
            phoneinfo:
                document.documentElement.clientWidth +
                "x" +
                document.documentElement.clientHeight,
            deviceinfo: scriptURI + " line:" + lineNumber,
        });
        //无法监听资源加载异常
    };
    //ajax 上报错误
    function reportException(info) {
        $.ajax({
            type: "POST",
            url: "ip/bug/add",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(info),
            success: function (reponse) {
            },
            error: function (e) {
                console.log("错误上报失败/bug/add");
            },
        });
    }
})();

标签: javascript

热门推荐