cdbeelala89
cdbeelala89

Reputation: 2146

catch errors thrown by child directives

My app is using some other directives I have no control other and I would like to augment any errors that come from those directives with some information, so that I know which errors are coming from myself and which are not. So I was trying to write my own directive, which compiles any content in a try/catch block so I can catch the errors and handle them appropriately.

I turns out the following code will not catch any errors, presumably because compile is executed asynchronously?

// in compile fn:
foreignEl = element.contents().remove();

// in link fn:
element.append(foreignEl);

try{
  $compile(foreignEl)(scope)
} catch(e){
  console.error("NOT MY FAULT: " + e.message);
}

I was thinking of using the directive like this:

<my-error-catcher>
  <the-foreign-directive>
  </the-foreign-directive>
</my-error-catcher>

Should this work?

Upvotes: 3

Views: 428

Answers (1)

yvesmancera
yvesmancera

Reputation: 2925

I tried your approach of creating a parent directive to catch child directives errors but got nowhere with it, but using decorators might be a more proper way of accomplishing your goal of catching errors thrown by directives you have no control of:

.config(function($provide) {
  $provide.decorator('theForeignDirective', function($delegate) {
    var directive = $delegate[0];
    //copy the directive's original link function
    var directiveLink = directive.link;

    directive.compile = function() {
      try {
        var bindedLink = directiveLink.apply(this, arguments);
        return function() {
          bindedLink.apply(this, arguments);
        };
      } catch(e) {
        console.error("NOT MY FAULT: " + e.message);
      }
    };

    return $delegate;

  });
});

Here is a working plunkr http://plnkr.co/edit/0Dk3DKhaNrxgSri5G54E

Upvotes: 2

Related Questions