2012-01-13 40 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