← Back to all snippets
JAVASCRIPT

Robust API Error Handling with `fetch` and `async/await`

Learn to build robust API calls using JavaScript's `fetch` API, `async/await`, and comprehensive error handling for network issues and HTTP status codes.

async function safeApiCall(url, options = {}) {
    try {
        const response = await fetch(url, options);

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
            throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorData.message || response.statusText}`);
        }

        return await response.json();
    } catch (error) {
        if (error instanceof TypeError && error.message === 'Failed to fetch') {
            console.error('Network error or CORS issue:', error.message);
            throw new Error('Network unavailable or CORS policy blocked the request. Please check your internet connection.');
        }
        console.error('API Call Failed:', error.message);
        throw error; // Re-throw for upstream handling
    }
}

// Example usage:
// safeApiCall('https://api.example.com/data')
//     .then(data => console.log('Data received:', data))
//     .catch(error => console.error('Caught in main:', error.message));

// safeApiCall('https://api.example.com/nonexistent', { method: 'POST', body: JSON.stringify({ item: 'test' }), headers: { 'Content-Type': 'application/json' } })
//     .catch(error => console.error('Caught in main (POST error):', error.message));
How it works: This snippet provides a reusable `safeApiCall` function that wraps the native `fetch` API with comprehensive error handling. It distinguishes between network/CORS issues (`TypeError: Failed to fetch`) and HTTP errors (non-`2xx` status codes). It attempts to parse JSON error responses and re-throws errors with informative messages, making API interactions more resilient and easier to debug.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs