仅捕获命名空间内的错误

时间:2014-06-25 07:51:50

标签: javascript sentry raven

是否可以配置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

2 个答案:

答案 0 :(得分:2)

您可以使用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,但由于某种原因仍未记录。

答案 1 :(得分:1)

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

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.
   }
}