You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何在WebSocket连接建立前调用close()会触发onerror?

Why calling close() before WebSocket connection is established triggers onerror?

Great question! Let me break down what's happening here and how to unpack the error details:

What's causing the error?

When you create a new WebSocket instance, it immediately enters the CONNECTING (readyState = 0) state while it tries to complete the handshake with the server. If you call close() at this point, the browser can't properly close a connection that hasn't been fully established yet. This abrupt termination of the pending connection attempt is treated as an error, which triggers the onerror event.

How to see the full error details?

Your current code throws the error, but to get concrete details, log the error object's properties directly in the onerror handler. Most browsers include useful context like a human-readable message, error code, and stack trace:

const connection = new WebSocket("wss://echo.websocket.org");
connection.onopen = () => { console.log('open'); }
connection.onerror = (error) => {
  console.error('Error Message:', error.message);
  console.error('Error Code:', error.code); // Typically 1006 for abnormal closure here
  console.error('Full Error Context:', error);
}
connection.close();

In Chrome, you’ll usually see a message like:

Failed to execute 'close' on 'WebSocket': The connection is not yet established

The error code 1006 signals an abnormal closure where no specific reason was provided by either the server or client.

How to avoid this error?

Just check the WebSocket's readyState before calling close() — only invoke it when the connection is either open or already in the process of closing:

const connection = new WebSocket("wss://echo.websocket.org");

connection.onopen = () => {
  console.log('open');
  // Safe to close here, no error will trigger
  connection.close();
};

connection.onerror = (error) => {
  console.error('Error:', error.message);
};

// Guard clause to prevent premature close
if (connection.readyState === WebSocket.OPEN || connection.readyState === WebSocket.CLOSING) {
  connection.close();
} else {
  console.log('Connection not fully established, skipping close to avoid error');
}

Is this expected behavior?

Absolutely! Per the WebSocket API specification, calling close() while the connection is in the CONNECTING state should abort the connection attempt, trigger the onerror event, and set the readyState to CLOSED. This is standard browser behavior, not a bug.

内容的提问来源于stack exchange,提问作者Yiou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:30:02