元渊 API元渊 API
Error Handling GuideError Scenarios

Scenario 5: Network & Timeout Errors

Handling network issues and timeouts

Error Types

Network Errors

NetworkError: Failed to fetch
TypeError: Network request failed
Error: ECONNREFUSED

Timeout Errors

Error: Request timeout
TimeoutError: Request aborted

Detection

function detectNetworkError(error) {
    const networkPatterns = [
        'NetworkError',
        'Failed to fetch',
        'ECONNREFUSED',
        'ETIMEDOUT'
    ];
    
    const message = error.message || '';
    return networkPatterns.some(p => message.includes(p));
}

Fetch with Timeout

async function fetchWithTimeout(url, options, timeout = 30000) {
    const controller = new AbortController();
    
    const timeoutId = setTimeout(() => controller.abort(), timeout);
    
    try {
        const response = await fetch(url, {
            ...options,
            signal: controller.signal
        });
        clearTimeout(timeoutId);
        return response;
    } catch (error) {
        clearTimeout(timeoutId);
        if (error.name === 'AbortError') {
            throw new Error('Request timeout');
        }
        throw error;
    }
}

Retry Strategy

async function retryWithStrategy(fn, options = {}) {
    const { maxRetries = 3, baseDelay = 1000 } = options;
    
    for (let attempt = 0; attempt < maxRetries; attempt++) {
        try {
            return await fn();
        } catch (error) {
            if (attempt === maxRetries - 1) throw error;
            
            const delay = baseDelay * Math.pow(2, attempt);
            await sleep(delay);
        }
    }
}

User Messages

Network Error

🌐 Network Error

Unable to connect to server. Please check your connection.

[Retry] [Cancel]

Timeout Error

⏱️ Request Timeout

Server response took too long.

[Retry] [Cancel]

Network Monitor

class NetworkMonitor {
    constructor() {
        this.online = navigator.onLine;
        window.addEventListener('online', () => this.handleOnline());
        window.addEventListener('offline', () => this.handleOffline());
    }
    
    isOnline() {
        return this.online;
    }
}

How is this guide?