JAVASCRIPT

Robust API Error Handling with JavaScript Fetch

Learn to implement comprehensive error handling for `fetch` API requests in JavaScript, covering network issues, HTTP status codes, and JSON parsing failures for reliable integrations.

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

        if (!response.ok) {
            let errorDetails = `HTTP error! Status: ${response.status}`;
            try {
                const errorData = await response.json();
                errorDetails += ` - ${JSON.stringify(errorData)}`;
            } catch (jsonError) {
                errorDetails += ` - Could not parse error response JSON: ${jsonError.message}`;
            }
            throw new Error(errorDetails);
        }

        const contentType = response.headers.get("content-type");
        if (contentType && contentType.includes("application/json")) {
            return await response.json();
        } else {
            return await response.text();
        }
    } catch (error) {
        console.error('Fetch operation failed:', error.message);
        throw error;
    }
}

// Example Usage:
// fetchDataWithErrorHandler('https://api.example.com/data')
//   .then(data => console.log('Success:', data))
//   .catch(err => console.error('Caught in usage:', err.message));

// fetchDataWithErrorHandler('https://api.example.com/nonexistent')
//   .then(data => console.log('Success:', data))
//   .catch(err => console.error('Caught in usage:', err.message));
How it works: This snippet provides a reusable asynchronous function for making `fetch` API requests with robust error handling. It checks `response.ok` for HTTP errors, attempts to parse error details from the response body, and catches network-level errors during the `fetch` operation. It also gracefully handles cases where the response might not be JSON, returning text or another content type.

Need help integrating this into your project?

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

Hire DigitalCodeLabs