Search code examples
htmlweb-worker

How to catch DataCloneError in Worker?


I have a HTML5 worker which sends values with postMessage. Sometimes (for example if the result is a function) the code throws an exception:

DataCloneError: The object could not be cloned.

So I tried to catch the exception:

try {
  self.postMessage (result);
}
catch (ex) {
  if (ex instanceof DataCloneError)
    self.postMessage (result.toString());
  else
    throw ex;
}

But this throws the following exception:

ReferenceError: DataCloneError is not defined

I am confused. How to catch the DataCloneError?


Solution

  • The error you receive is an instance of the DOMException interface.

    To know which DOMException it is, you can check its name property.
    The one of DATA_CLONE_ERROR, is "DataCloneError".

    try {
      postMessage( () => {} , '*' );
    }
    catch( err ) {
      console.log( err.name === "DataCloneError" );
    }