Is there a global browser object I can add a listener to catch all thrown errors?

I’m using Selenium to crawl an AngularJS site and would like to create a list of all thrown errors (the specific errors I’m actually interested in are these lex errors). AngularJS exposes $exceptionHandler to overwrite exception handling behavior. But would rather stay away from modifying app code as much as possible as these are remote tests.

I’m using Firefox so browser.manage().logs() fails. I suspect this question is closely related to Log console errors using protractorthis SO answer.

I have tried window.onerror and window.addEventListener('error', () => { ... }); but neither of them catch the thrown error. I wonder if there is something that AngularJS is doing that blocks propagation to the window maybe?

My goal:

window.thrownErrors = [];
[Some global object].throw = (error) => {
  console.error(error);
  window.thrownErrors.push(error);
}

throw new Error('throw test');
console.log(window.thrownErrors); // => ['throw test']

Answer

Use the useCapture option when adding the event handler:

window.addEventListener('error', () => { ... }, true);

The third argument can be a Boolean indicating whether events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events that are bubbling upward through the tree will not trigger a listener designated to use capture. Event bubbling and capturing are two ways of propagating events that occur in an element that is nested within another element, when both elements have registered a handle for that event. The event propagation mode determines the order in which elements receive the event. See DOM Level 3 Events and JavaScript Event order for a detailed explanation. If not specified, useCapture defaults to false.

For more information, see