How to detect errors of invalid URL in Worker API

試著忘記壹切 提交于 2019-12-24 03:43:07

问题


If I run the following (at least on Chromium):

var w = null;
try {
    w = new Worker( 'NONEXISTENT_URL' );
}
catch ( e ) {
    console.log( 'CAUGHT: ' + e );
}
console.log( w );

...no exception is caught, even though the argument to the Worker constructor does not point to a valid filename. Moreover, the console shows Worker {}, indicating that w now holds a (non-functional) instance of Worker.

Other error conditions are also possible. For example, argument to the constructor may be available and readable, but not contain valid JavaScript.

How else can I detect such error conditions?

(BTW: Please assume that the browser supports the Worker API.)


回答1:


You can get error using onerror event handler.

var worker = new Worker('aURL');

worker.onerror = function () {
    console.log( 'error' );
};

If the URL has an invalid syntax or if the same-origin policy is violated a DOMException of type SECURITY_ERR is thrown.



来源:https://stackoverflow.com/questions/32102658/how-to-detect-errors-of-invalid-url-in-worker-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!