2

在下面的示例中,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>

网络工作者(foo.js):

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

1 回答 1

1

您可以异步处理工作人员中的错误。你需要听error工人的事件。

worker.addEventListener("错误", onError, false);

这里有一个关于网络工作者的很棒的教程。您可以在该部分中准确找到您要查找的handling errors内容。

您还可以查看官方html5 规范以获取有关浏览器应如何实现此功能的更多信息。

于 2012-09-11T11:57:24.747 回答