2012-01-13 57 views
1
window.onerror = function(type, file, line){ 
     if(type) { 
      console.log(type); 
     } 
     if(file) { 
      console.log(file); 
     } 
     if(line) { 
      console.log(line); 
     } 
    } 

当某些.js文件出现错误时,此代码返回“脚本错误”。我需要错误的类型,文件和行。我怎么才能得到它? 当窗口抛出错误时,这个脚本完美地工作,但当.js文件出现错误时它不一样。 我知道,我可以在控制台上找到这些东西,但想象我没有一个,我无法安装。脚本错误 - 类型,行和文件

回答

1
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 
} 
+0

我没有看到你的代码和我引用的代码之间有太大的区别。 – Nikolay 2012-01-16 07:41:09

-1

下面是我用来捕捉错误。我有它请求一个图像的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 */ 
    } 
    } 

}; 
+0

看看window.onerror事件中对logJSErrors的调用。它包含所有的错误信息。这是一个散列。为什么这是downvoted? – 2012-01-13 15:19:42

+0

当我在javascript中遇到问题时,再次只显示“脚本错误”。这与我的代码没有多大区别,对我来说没有用处 – Nikolay 2012-01-16 07:59:59

+0

嗯。这个脚本适合我。是否可以发布一个链接到你的开发?或者把你的网页放在jsfiddle.net上?在这一点上,我需要明白为什么它不起作用。 – 2012-01-16 14:01:19