【问题标题】:Capture only errors that are within namespace仅捕获命名空间内的错误
【发布时间】:2014-06-25 07:51:49
【问题描述】:

是否可以将raven-js 配置为忽略不在定义命名空间内的错误?

var Foo = Foo || {};

Foo.raiseWithinNamespace = function(){
   //bar is not defined, raises
   return bar;
}

function raiseOutOfNameSpace(){
   //bar is not defined, raises
   return bar;
}

所以Foo.raiseWithinNamespace 将被捕获,raiseOutOfNameSpace 将被忽略。

【问题讨论】:

    标签: javascript sentry raven


    【解决方案1】:

    你可以简单地用Raven.wrap()创建的包装器替换命名空间中的每个函数:

    // Do not catch global errors
    Raven.config(..., {collectWindowErrors: false}).install()
    
    // Helper to catch exceptions for namespace
    function catchInNamespace(ns)
    {
      for (var key in ns)
      {
        if (ns.hasOwnProperty(key) && typeof ns[key] == "function")
          ns[key] = Raven.wrap(ns[key]);
      }
    }
    
    // Declaration of namespace Foo
    var Foo = Foo || {};
    Foo.func1 = ...;
    Foo.func2 = ...;
    catchInNamespace(Foo);
    
    // Using namespace
    Foo.func1();   // Any exceptions here are caught by Raven.js
    

    请注意,collectWindowErrors: false 配置选项是忽略来自其他命名空间和全局函数的错误所必需的,没有它,Raven.js 将隐式捕获所有异常。此选项为 introduced in Raven.js 1.1.0,但由于某种原因仍未记录在案。

    【讨论】:

      【解决方案2】:

      这可以使用类继承来完成。

      function capture_exception_iff(){};
      //Errors will only be captured in Foo and A.
      var Foo = Foo || new capture_exception_iff();
      var A = A || new capture_exception_iff();
      var B = B || {};
      
      
      function Raven_capture_exception(e){
          if(this instanceof capture_exception_iff){
              Raven.captureException(e)
          }  
      }
      
      Foo.raiseWithinNamespace = function(){
         try {
            return bar;
         } catch(e) {
            Raven_capture_exception(e)
            //it will pass the if-statement 
            //Raven.captureException(e) will be called.
         }
       }
      
      B.raiseWithinNamespace = function(){
         try {
            return bar;
         } catch(e) {
            Raven_capture_exception(e)
            //it will not pass the if-statement 
            //Raven.captureException(e) will not be called.
         }
       }
      
      function raiseOutOfNameSpace(){
         try {
            return bar;
         } catch(e) {
            Raven_capture_exception(e)
            //it will not pass the if-statement
            //Raven.captureException(e) will not be called.
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-11-15
        • 1970-01-01
        • 2020-09-04
        • 2019-08-11
        • 1970-01-01
        • 2013-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多