Async Error Handling in JavaScript
Level 5676 keystrokes
This implements retry logic with async/await for handling transient failures.
JavaScript code
// Fetch with automatic retry on failure1async function fetchWithRetry(url, retries = 3) { // Try up to 'retries' times2 for (let i = 0; i < retries; i++) {3 try {4 console.log(`Attempt ${i + 1}...`); // Wait for fakeFetch; if it rejects, control jumps to catch5 const response = await fakeFetch(url); // Success - return immediately6 return response;7 } catch (error) {8 console.log(`Failed: ${error.message}`); // If this was the last attempt, throw the error9 if (i === retries - 1) throw error; // Wait before retrying (exponential backoff could be used)10 await delay(1000);11 }12 }13}14 // Simple delay helper15function delay(ms) {16 return new Promise(r => setTimeout(r, ms));17}18 // Simulate a failing API that succeeds on 3rd attempt19let attempts = 0;20function fakeFetch(url) {21 return new Promise((resolve, reject) => {22 attempts++; // Fail first 2 attempts, succeed on 3rd23 if (attempts < 3) reject(new Error("Network error"));24 else resolve({ data: "Success!" });25 });26}27 // Call the retry function; then prints the result, catch prints the final error28fetchWithRetry("api/data")29 .then(data => console.log(data))30 .catch(err => console.log("Final error:", err));Output
Attempt 1...
Failed: Network error
Attempt 2...
Failed: Network error
Attempt 3...
{ data: 'Success!' }Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
(× 23)× 23;× 15=× 11.× 10{× 10}× 10"× 8+× 5,× 4