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:
- Stop processing the message
- Send Close frame with status code 1007
- Close the connection
Other Common Errors
Protocol Violations
| Error Type | Close Code | Handling |
|---|---|---|
| Received unmasked client frame | 1002 | Immediately close connection |
| Received masked server frame | 1002 | Immediately close connection |
| Invalid Opcode | 1002 | Immediately close connection |
| Fragmented control frame | 1002 | Immediately close connection |
| Control frame exceeds 125 bytes | 1002 | Immediately close connection |
| Invalid UTF-8 | 1007 | Send Close frame then close |
| Message too large | 1009 | Send 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);
}
});
Reference Links
- Previous Chapter: 7. Closing the Connection
- Next Chapter: 9. Extensions