How to bubble a web worker error in a promise via worker.onerror?

后端 未结 1 1864
灰色年华
灰色年华 2021-01-05 21:35

I\'m dealing with a web worker that needs to report back if an error has occured. Normally, I can use worker.onerror to listen to any errors that were thrown fr

1条回答
  •  天命终不由人
    2021-01-05 22:10

    postMessage doesn't work for some reason

    That's because you're returning an object instead of a string, change it to self.postMessage({error: err.message});

    As for your second problem, you can use the setTimeout(function() { throw err; }); trick. More information about the situation and trick can be found here.

    function getInlineJS() {
      var js = document.querySelector('[type="javascript/worker"]').textContent;
      var blob = new Blob([js], {
        "type": "text\/plain"
      });
      return URL.createObjectURL(blob);
    }
    
    var worker = new Worker(getInlineJS());
    
    worker.onerror = function(err) {
      document.getElementById('errors').innerHTML += 
        "error " + err.message + '\n';
    }
    
    worker.onmessage = function (msg) {
      console.log("message recieved", msg);
      document.getElementById('messages').innerHTML += 
        "message " + msg.data + '\n';
    }
    
    
    worker.postMessage("run");
    worker.postMessage("promise");
    should write "Normal Error and In Promise Error" below and in console (promise error only occurs in console though): 
    
    
    messages:
    
    
    
    

    0 讨论(0)
提交回复
热议问题