以下の例では、web worker のコードにエラー (未定義の参照) がありますが、try { ... } catch(e) { ...}はあまりキャッチしません。メッセージなぜ私はここにいるの?コンソールに表示されます。
HTML ファイル:
<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 ワーカー ( foo.js ):
foobar = 2 + baz; // fails here (baz is undefined)
onmessage = function(e) {
var data = e.data;
postMessage(data);
};