【问题标题】:jQuery exception handlingjQuery 异常处理
【发布时间】:2010-06-21 13:12:22
【问题描述】:

有什么方法可以在 javascript 中捕获任何未捕获的异常?我的意思是,我所有的“危险”代码都在 try-catch 块中。但是我没有明确处理的异常呢?我正在使用 jQuery,我的主要 javascript 文件以:

开头

$(document).ready(function(){})

这里我将一些事件绑定到一些 DOM 元素。我可以在这里使用 try-catch 块,但它们将捕获在事件绑定过程中发生的异常,而不是在事件处理期间。但是,如果我在每个事件处理函数中都使用 try-catch 块,那就太难看了。

我应该如何捕获在我的显式 try-catch 块中未发生的异常? (我不想写一个通用的处理函数,我只想将问题发送到我的服务器)

【问题讨论】:

    标签: javascript jquery exception-handling


    【解决方案1】:

    您可以编写一个函数,将您的真实处理程序包装在 try/catch 中

    function tc(func, msg) {
      msg = msg || "Handler exception";
      return function(e) {
        try {
          return func(e);
        }
        catch (exc) {
          $.post( /* send exception to server? */ );
          throw exc; // let nature take its course
        }
      };
    }
    

    (可能希望对参数处理等进行更高级的处理)然后当您绑定处理程序时,您会这样做:

    $('#whatever').click(tc(function(e) {
      // your handler function
    }, "This is the message sent to the server when this handler fails"));
    

    此外,如果您想确保处理程序中的“this”的行为与以前一样,您可以使用func.apply($(this), e) 而不仅仅是func(e)。

    【讨论】:

      【解决方案2】:

      您可以使用 window.onerror 事件处理程序,但 Opera 和 it may not fire in certain situations 不支持它(感谢 @Josh)。

      这样做并不明智,但是,它会让寻找错误开始成为一场噩梦。通常最好首先确保您的代码没有错误 :-) 您当然不需要在 JavaScript 中经常使用 try... catch 语句,而且您绝对不应该使用空的 catch 块。

      我可以在这里使用 try-catch 块,但是它们将捕获在事件绑定过程中发生的异常,而不是在事件处理期间。

      您还可以将 try/catch 块添加到内部范围:

      // Outer
      try { 
          $(document).ready(function(){})
      }
      catch (e) {
          /* Error handling */
      }
      
      // Inner
      $(document).ready(function(){
          try { /* ... */ } catch (e) { /* Error handling */ }
      });
      

      【讨论】:

      【解决方案3】:

      怎么样

          function func_madness() {
              throw("This function is throwing exceptions, because \n" +
              "it can not throw polar bears and whales.\n");
          } // func_madness
      
          window.onload = function () {
              try {
                  func_madness();
              } catch (err) {
                  document.write("Caught it!\n<br/>\n" + err);
              } // catch
          } // window.onload
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-18
        • 1970-01-01
        • 1970-01-01
        • 2012-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多