捕获脚本错误 - 类型,行和文件

Catch script error - type,line and file

本文关键字:文件 类型 脚本错误      更新时间:2023-09-26
window.onerror = function(type, file, line){
        if(type) {
            console.log(type);
        }
        if(file) {
            console.log(file);
        }
        if(line) {
            console.log(line);
        }
    }

当某些.js文件出错时,此代码返回"脚本错误"。我需要错误的类型,文件和行。我怎样才能得到它?当窗口抛出错误时,此脚本可以完美运行,但当.js文件中存在错误时,它就不一样了。我知道我可以在控制台上找到这些东西,但想象一下我没有,也无法安装。

window.onerror = ErrorLog;
function ErrorLog (msg, url, line) {
    console.log("error: " + msg + "'n" + "file: " + url + "'n" + "line: " + line);
    return true; // avoid to display an error message in the browser
}

Chrome和Firefox中Javascript中报告的神秘"脚本错误"帖子应该可以回答您的"脚本错误"问题。 也就是说,它可能是由"同源政策"引起的。

虽然我仍在寻找为什么 webkit 会给我"未定义"的文件名和"0"行号以用于未捕获的异常。

这是我用来捕获错误的方法。 我让它请求一个 url 指向服务器端脚本的图像。

function logJSErrors(errObj) {
  if (!errObj || !errObj.lineNumber || errObj.lineNumber == 0) {
    return; // can't use it any way.
  }
  if (window.location && window.location.toString().indexOf('rfhelper32.js') >= 0) {
    return; // ignore the stupid Norton/Firefox conflict
  }
  var img = new Image();
  img.src = "/jserror?m=" + encodeURIComponent(errObj.message) +
      "&location=" + encodeURIComponent(window.location) +
      "&ln=" + encodeURIComponent(errObj.lineNumber) +
      "&url=" + encodeURIComponent(errObj.fileName) +
      "&browser=" + encodeURIComponent(errObj.browserInfo);
}
window.onerror = function (msg, url, line) {
  logJSErrors({ message : msg,
    lineNumber : line,
    fileName : url,
    browserInfo : window.navigator.userAgent
  });
  // if a jquery ajax call was running, be sure to make the spinning icons go away
  if (jQuery) {
    try {
      jQuery.event.trigger("ajaxStop");
    } catch(e) {/* do nothing */
    }
  }
};