问题
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