Search code examples
javascriptsentryraven

Capture only errors that are within namespace


Is it possible to configure raven-js to ignore errors that are not within a defined namespace?

var Foo = Foo || {};

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

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

So Foo.raiseWithinNamespace would be captured and raiseOutOfNameSpace would be ignored.


Solution

  • You can simply replace each function in the namespace by a wrapper created by 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
    

    Note that collectWindowErrors: false configuration option is required to ignore errors from other namespaces and global functions, without it Raven.js will catch all exceptions implicitly. This option has been introduced in Raven.js 1.1.0 but still isn't documented for some reason.