2

I am trying to test some code that uses web workers. I want to check that the error path works; i.e., that an onError handler correctly recovers from an exception thrown in the web worker.

The problem I'm running into is that the exception propagating out of the web worker causes it to be considered unhandled. For example, it prints in the browser's console log and causes my testing environment (a simple wrapper around Karma) to consider the test as failed.

So, How do I indicate to the browser/Karma that an exception bubbling out of a given web worker is expected, and should not be considered unhandled? I don't want it to print to the console, and I want my test to pass.

The only idea I've come up with is to wrap the web worker code in a try/catch and marshal the caught exception out via postMessage, but that requires throwing away quite a lot of information because of the need to stringify the error object (otherwise it triggers a data clone error).

Community
  • 1
  • 1
Craig Gidney
  • 17,763
  • 5
  • 68
  • 136

1 Answers1

4

Call preventDefault on the error event object given to the onError handler.

worker.onError = function(e) {
    e.preventDefault(); // <-- "Hey browser, I handled it!"
    ...
}
Craig Gidney
  • 17,763
  • 5
  • 68
  • 136
  • Man, with this answer you did 2 things: 1. made my last 3 days totally unproductive 2. you saved me another X days of unproductive searching of where is the error leaking THANK YOU! – Dracco Feb 25 '19 at 20:00