gpt4 book ai didi

javascript - 共享网络 worker 错误处理

转载 作者:行者123 更新时间:2023-11-28 19:36:34 29 4
gpt4 key购买 nike

如何在共享 Web Worker 中处理/抛出错误?

如果您在专用 Web Worker 中抛出这样的错误,该错误会出现在浏览器的控制台中..但在共享 Worker 时不会出现..!?

使用专用 Web Worker,您还可以在 Worker 中使用 console.log()。但不能在共享 Web Worker 中使用

主页

var worker = new SharedWorker('js/webworker.js');

worker.port.onmessage = function(e){
console.log('From worker: '+e.data);
};

worker.port.onerror = function(e){
console.log(e.message+'\nLine: '+e.lineno+'\nFilename: '+e.filename);
};

worker.port.start();

worker.port.postMessage('This message should throw an error in the web worker');

共享网络 worker

var ports = [];

self.onconnect = function(e){
var port = e.ports[0];
ports.push(port);

port.onmessage = function(e){
port.postMessage(e.data);

throw Error('hehehe');
};

port.start();

port.postMessage('Worker connected!');
};

最佳答案

正如文档所述:

Whenever an uncaught runtime script error occurs in one of the worker's scripts, if the error did not occur while handling a previous script error, the user agent must report the error at the URL of the resource that contained the script, with the position (line number and column number) where the error occurred, in the origin of the scripts running in the worker, using the WorkerGlobalScope object's onerror attribute.

http://www.w3.org/TR/workers/

因此错误将报告给self,然后发送到所有端口:

self.onerror = function (e) {
ports.forEach(function (port) { port.postMessage(e); });
};

这里是 jsfiddle 演示它:http://jsfiddle.net/nhrfgd1L/

关于javascript - 共享网络 worker 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25776240/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com