Is onclose always called after onerror for WebSocket

javascript, websocket

Solution

The `error` event will only ever be fired prior to then also firing the `close` event, at least by implementations that properly implement the specification, i.e. you will get `error` and `close` as a pair, or just `close` by itself.

The process for closing a websocket consists of 3 steps, the second of which optionally fires the `error` event if needed:

- If the user agent was required to fail the WebSocket connection, or if the the WebSocket connection was closed after being flagged as full, fire a simple event named `error` at the WebSocket object. [WSP]

Before the third step then calls close:

- Fire an event named `close` at the WebSocket object, using `CloseEvent`,...

And because both of these steps are one after the other inside the same queued task, your event handlers should be invoked one after the other, with no other events or tasks taking place in between them.

Problem

Is it possible that the onerror callback can be called where onclose will not be called immediately after? In other words, is it possible to get a `WebSocket` error which does not coincide with the connection then being closed? If it is possible, I would like to test this case. I have a mocked backend which uses node.js and express-ws. What can I do in the backend to trigger the onerror event callback in the front end.

Original source