8. 错误处理
8.1 处理 UTF-8 编码数据中的错误
接收文本帧 (Text frame, Opcode 0x1) 时, 有效载荷数据必须是有效的 UTF-8 编码文本.
验证 UTF-8
实现 MUST 验证收到的文本数据是有效的 UTF-8.
function isValidUTF8(buffer) {
try {
// Node.js throws an error on invalid UTF-8
const str = buffer.toString('utf8');
// Verify round-trip conversion
return Buffer.from(str, 'utf8').equals(buffer);
} catch (e) {
return false;
}
}
ws.on('message', (data, isBinary) => {
if (!isBinary && !isValidUTF8(data)) {
// Close code 1007 = Invalid frame payload data
ws.close(1007, 'Invalid UTF-8 in text frame');
}
});
错误处理流程
检测到无效 UTF-8 时:
- 停止处理该消息
- 发送状态码为 1007 的 Close frame
- 关闭连接
其他常见错误
协议违规
| 错误类型 | Close Code | 处理方式 |
|---|---|---|
| 收到未掩码的客户端帧 | 1002 | 立即关闭连接 |
| 收到已掩码的服务器帧 | 1002 | 立即关闭连接 |
| 无效 Opcode | 1002 | 立即关闭连接 |
| 分片的控制帧 | 1002 | 立即关闭连接 |
| 控制帧超过 125 字节 | 1002 | 立即关闭连接 |
| 无效 UTF-8 | 1007 | 发送 Close frame 后关闭 |
| 消息过大 | 1009 | 发送 Close frame 后关闭 |
错误处理最佳实践
ws.on('error', (error) => {
console.error('WebSocket error:', error);
// Log error
// Notify monitoring system
});
ws.on('close', (code, reason) => {
if (code !== 1000 && code !== 1001) {
console.error(`Abnormal closure: ${code} - ${reason}`);
// Implement reconnection logic
setTimeout(() => reconnect(), 5000);
}
});