Error Handling with Invalid Byte Sequences
You'll learn how TextDecoder handles malformed UTF-8 sequences and how to control whether it substitutes replacements or throws errors.
The Problem with Malformed Data
When working with binary data from external sources—network responses, file uploads, third-party APIs—you can't always trust the bytes are valid UTF-8. Sometimes you'll encounter incomplete sequences or outright gibberish. TextDecoder needs a strategy for dealing with these cases.
Two Error Handling Modes
By default, TextDecoder is forgiving. When it encounters an invalid byte sequence, it replaces it with the Unicode replacement character � (U+FFFD) and continues decoding. This prevents your application from crashing but quietly masks data corruption.
For stricter validation, pass { fatal: true } when creating the decoder:
const decoder = new TextDecoder('utf-8', { fatal: true });
const validBytes = new Uint8Array([72, 105]); // "Hi"
const invalidBytes = new Uint8Array([72, 0xFF, 105]); // 0xFF is invalid UTF-8
console.log(decoder.decode(validBytes)); // "Hi"
try {
decoder.decode(invalidBytes);
} catch (err) {
console.log(err.name); // "TypeError"
console.log('Decoding failed due to invalid bytes');
}
When to Use Fatal Mode
Use fatal: true when data integrity is critical—cryptographic signatures, file format parsers, or protocol implementations where corruption must be detected immediately. Use the default lenient mode when you're displaying user-generated content and prefer showing something over crashing.
Key Takeaway: TextDecoder defaults to replacing invalid bytes with �, but setting { fatal: true } makes it throw a TypeError instead, letting you detect and handle corruption explicitly.