Search code examples
htmlerror-handlingweb-worker

Is is possible to catch if the creation of a web worker if failing?


In the example below there is in an error in the code for the web worker (undefined reference) but try { ... } catch(e) { ...} does not catch much. The message Why am I here ? appears on the console.

HTML file:

<html>
<body>
<script type="text/javascript">

var worker;
try {
  worker = new Worker("foo.js");
  console.log('Why am I here ?');
} catch (e) {
  console.log('Error creating the worker.');
}
// No matter what, an object "worker" will created during the call to Worker()
// How to test that all went well
var worker_failed = false;
worker.addEventListener("error",
                        function(e) { worker_failed = true },
                        false);
// Is it correct to assume that "worker" is created asynchronously, and that checking
// that creation went well should not be sequential and the test below is not
// the way to do it ?
if ( worker_failed ) {
  // Worker("foo.js") failed, switch to plan B
}
</script>
</body>
</html>

Web worker (foo.js):

foobar = 2 + baz; // fails here (baz is undefined)
onmessage = function(e) {
  var data = e.data;
  postMessage(data);
};

Solution

  • You can handle errors in your workers asynchronously. You need to listen to the error event of the worker.

    worker.addEventListener("error", onError, false);

    There's a great tutorial about web workers here. You can find exactly what you're looking for in the handling errors section.

    You can also check the official html5 spec for more information about how this should be implemented by the browsers.