Skip to main content

8. Error Handling

8.1 Handling Errors in UTF-8-Encoded Data

When receiving a Text frame (Opcode 0x1), the payload data must be valid UTF-8 encoded text.

Validating UTF-8

Implementations MUST validate that received text data is valid 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');
}
});

Error Handling Process

When invalid UTF-8 is detected:

  1. Stop processing the message
  2. Send Close frame with status code 1007
  3. Close the connection

Other Common Errors

Protocol Violations

Error TypeClose CodeHandling
Received unmasked client frame1002Immediately close connection
Received masked server frame1002Immediately close connection
Invalid Opcode1002Immediately close connection
Fragmented control frame1002Immediately close connection
Control frame exceeds 125 bytes1002Immediately close connection
Invalid UTF-81007Send Close frame then close
Message too large1009Send Close frame then close

Error Handling Best Practices

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);
}
});