2
在下面的示例中,web worker的代碼中存在錯誤(未定義的引用),但嘗試{...} catch(e){...}沒有太多內容。消息我爲什麼在這裏?控制檯上出現。如果失敗,是否有可能捕捉到Web工作者的創建?
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);
};
但是這個錯誤是在工作人員創建後被捕獲的。序列如下:var worked = Worker('foo.js'); worker.addEventListener(「error」,onError,false); – lgautier
儘管嘗試了一個偵聽器onError確實收到錯誤...並且控制檯也收到錯誤。 – lgautier
如果你不想讓錯誤進入控制檯,你應該在工作人員自己看到它。正如規範所述,_只要在其中一個工作人員的腳本中出現未捕獲的運行時腳本錯誤,用戶代理就必須在包含script_的資源的URL處報告錯誤。 chrome調試器可能正在以與你一樣的方式監聽'error'事件並將該信息傳遞給控制檯。 – jbalsas