Quick Answer

Handle malformed URI component errors.

Understanding the Issue

URIError occurs when global URI handling functions (decodeURI, decodeURIComponent) encounter malformed sequences. This typically happens with improperly encoded strings or binary data.

The Problem

This code demonstrates the issue:

Javascript Error
const encoded = '%E0%A4%A';
decodeURIComponent(encoded); // Fails

The Solution

Here's the corrected code:

Javascript Fixed
// Solution 1: Try/catch
try {
    const decoded = decodeURIComponent(encoded);
} catch (e) {
    console.error('Invalid URI:', e);
}

// Solution 2: Validate first
function safeDecode(uri) {
    try {
        return decodeURIComponent(uri);
    } catch {
        return uri; // or handle differently
    }
}

// Solution 3: Use URLSearchParams for query strings
const params = new URLSearchParams('query=test%20value');
const query = params.get('query');

Key Takeaways

Always validate and handle errors when working with URI components.