JAVASCRIPT

Robust API Fetching with Async/Await and Error Handling

Learn how to make reliable API requests in JavaScript using the modern `fetch` API, `async/await` for cleaner asynchronous code, and comprehensive error handling.

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

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({ message: response.statusText }));
      throw new Error(`HTTP error! Status: ${response.status}, Details: ${JSON.stringify(errorData)}`);
    }

    const data = await response.json();
    return data;
  } catch (error)
  {
    console.error('API Request Failed:', error);
    throw error; // Re-throw to allow caller to handle
  }
}

// Example Usage:
// fetchData('https://api.example.com/data')
//   .then(data => console.log('Fetched Data:', data))
//   .catch(error => console.error('Failed to fetch:', error));

// Example with POST request:
// fetchData('https://api.example.com/items', {
//   method: 'POST',
//   headers: {
//     'Content-Type': 'application/json',
//     'Authorization': 'Bearer YOUR_TOKEN'
//   },
//   body: JSON.stringify({ name: 'New Item', value: 123 })
// })
//   .then(data => console.log('Created Item:', data))
//   .catch(error => console.error('Failed to create:', error));
How it works: This snippet provides a reusable `fetchData` function that wraps the standard `fetch` API with `async/await` for better readability. It includes robust error handling by checking `response.ok` for HTTP errors and attempting to parse the error body. If the `fetch` operation fails due to network issues or invalid URLs, it catches the error and logs it, then re-throws it for the calling code to handle gracefully.

Need help integrating this into your project?

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

Hire DigitalCodeLabs