Fetch API and Error Handling in JavaScript
JavaScript Event Handling: Exercise-18 with Solution
Fetch API with Error Handling
Write a JavaScript program that fetches data from an API, handles network errors, and displays the results on a webpage
Solution 1: Using fetch data from an API
JavaScript Code:
Output:
Fetch Data Post 1: sunt aut facere repellat provident occaecati excepturi optio reprehenderit Post 2: qui est esse Post 3: ea molestias quasi exercitationem repellat qui ipsa sit aut Post 4: eum et est occaecati Post 5: nesciunt quas odio
Explanation:
- Uses the fetch API inside a try-catch block for better error handling.
- Checks if the response is not OK and throws an error with the HTTP status.
- Catches both network errors and non-200 responses.
- Dynamically displays the first 5 posts in a styled div.
- Adds a button to trigger the fetch operation, ensuring flexibility.
1. Fetching Data:
2. Error Handling:
3. Display Results:
4. User Interaction:
Solution 2: Using Fetch with Promises
JavaScript Code:
Output:
Fetch Data Post 1: sunt aut facere repellat provident occaecati excepturi optio reprehenderit Post 2: qui est esse Post 3: ea molestias quasi exercitationem repellat qui ipsa sit aut Post 4: eum et est occaecati Post 5: nesciunt quas odio
Explanation:
- Uses the fetch API with Promises (then and catch) for handling asynchronous behavior.
- Throws an error for non-200 HTTP responses and catches it in the catch block.
- Dynamically displays the first 5 posts in a styled div.
- Adds a button to trigger the fetch operation, ensuring the user initiates the request.
1. Fetching Data:
2. Error Handling:
3. Display Results:
4. User Interaction:
Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript program that fetches data from a public API, checks for HTTP errors, and displays a custom error message if needed.
- Write a JavaScript function that uses the Fetch API to retrieve data, implements a timeout for the request, and handles errors gracefully.
- Write a JavaScript program that fetches JSON data from an API and retries the request upon encountering network errors.
- Write a JavaScript function that parses API responses and uses try-catch to handle JSON parsing errors.
Improve this sample solution and post your code through Disqus.
Event Handling Exercises Previous: Build a Shopping Cart using JavaScript and SessionStorage.
Event Handling Exercises Next: Geolocation API in JavaScript for user Location Access.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.