如何捕获javascript异常/错误? (在服务器上记录它们)

时间:2022-10-28 13:08:46

Duplicate:


How would I go about logging errors in javascript? I can't wrap every line of javascript in try catch block.

我如何在javascript中记录错误?我无法在try catch块中包装每一行javascript。

I talking about the errors that for example in IE, would show an Error On page message and have the line and char the caused the error. If I can just figure out how to catch this error on the client side, I can just log the error on the server using an ajax call.

我在谈论错误,例如在IE中,会显示错误页面消息,并且行和char导致错误。如果我能弄清楚如何在客户端捕获此错误,我可以使用ajax调用在服务器上记录错误。

1 个解决方案

#1


I use this function in all my projects:

我在所有项目中使用此功能:

window.onerror = function(m,u,l){
    jQuery.post("ajax/js_error_log.php",
        { msg: m,
          url: u,
         line: l,
       window: window.location.href });
    return true};

Make sure it is the very first javascript the browser receives or at least precedes any potentially error-causing code. Requires jQuery of course, but you could code ajax functions in pure javascript if you wanted to.

确保它是浏览器收到的第一个javascript,或者至少在任何可能导致错误的代码之前。当然需要jQuery,但如果你愿意的话,你可以用纯JavaScript编写ajax函数。

Please note: this will not help you if you have a syntax error. All javascript instantly dies if there is a syntax error.

请注意:如果您遇到语法错误,这对您没有帮助。如果存在语法错误,所有javascript会立即死亡。

#1


I use this function in all my projects:

我在所有项目中使用此功能:

window.onerror = function(m,u,l){
    jQuery.post("ajax/js_error_log.php",
        { msg: m,
          url: u,
         line: l,
       window: window.location.href });
    return true};

Make sure it is the very first javascript the browser receives or at least precedes any potentially error-causing code. Requires jQuery of course, but you could code ajax functions in pure javascript if you wanted to.

确保它是浏览器收到的第一个javascript,或者至少在任何可能导致错误的代码之前。当然需要jQuery,但如果你愿意的话,你可以用纯JavaScript编写ajax函数。

Please note: this will not help you if you have a syntax error. All javascript instantly dies if there is a syntax error.

请注意:如果您遇到语法错误,这对您没有帮助。如果存在语法错误,所有javascript会立即死亡。