Mikko Rantalainen
Mikko Rantalainen

Reputation: 16015

How to handle all WebSocket errors without a race?

When I run code

var ws = new WebSocket("wss://mydomain.example/socket/service");
ws.addEventListener("error", function (error)
{
  console.error("Got error=", error);
});

Is it possible that the WebSocket connection fails (emit error) before I can attach the event listener for the error event?

Looking at the documentation https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket I cannot see this detail documented anywhere.

According to the WHATWG spec it seems that the constructor should run the request in parallel – is there a guarantee that I can attach the error listener before any possible errors can raise?

Upvotes: 0

Views: 1357

Answers (1)

Mikko Rantalainen
Mikko Rantalainen

Reputation: 16015

The WebSocket constructor is run without synchronization of any kind and the connection may indeed encounter an error before the line with ws.addEventListener("error", ...); is executed! However, this is not a problem because the spec also says that in case of error, the actual error event is fired as a part of steps that must be queued as a task. In practice, this means that logically the WebSocket constructor is required to behave as if it would run an anonymous function with zero timeout which fires the error event.

So the actual error can happen before the JS code can attach the event listener but all the events (open, close, error, message) can only be fired delayed after the event loop is executed next time so the above code will always have to time attach the event handlers before the events can be fired.

See https://github.com/whatwg/websockets/issues/13#issuecomment-1039442142 for details.

Upvotes: 1

Related Questions