WebSocket: error event
The error event fires when the connection fails, or drops after it was established. It is always followed by a close.
Syntax
ws.addEventListener('error', (event) => { })Event object
WebSocketErrorEvent in the type definitions. Cannot be canceled.
message
A string: the error description given by the system. It is human-readable text in the language of the system settings; do not base decisions on it.
When it fires
- The connection fails: the host does not exist, there is no network, or the server rejects the handshake.
- The connection drops after it was established.
- Both cases fire the same event. Whether
openfired tells them apart: if it never fired, the connection failed. closefires right after, withcode1006andwasCleanfalse. Cleanup code only needs to go in theclosecallback.
Examples
js
const ws = new WebSocket('wss://echo.websocket.org');
let opened = false;
ws.addEventListener('open', () => { opened = true; });
ws.addEventListener('error', (e) => {
const reason = /** @type {WebSocketErrorEvent} */ (e).message;
console.log(opened ? 'Dropped' : 'Failed to connect', reason);
});Effect: when the connection errors, logs Failed to connect or Dropped, followed by the system's error description.
Differences from the web
- The browser's
errorevent carries no reason; here it carriesmessage. - There is no
onerrorproperty; onlyaddEventListenerworks.