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 failure
1async function fetchWithRetry(url, retries = 3) {
// Try up to 'retries' times
2 for (let i = 0; i < retries; i++) {
3 try {
4 console.log(`Attempt ${i + 1}...`);
// Wait for fakeFetch; if it rejects, control jumps to catch
5 const response = await fakeFetch(url);
// Success - return immediately
6 return response;
7 } catch (error) {
8 console.log(`Failed: ${error.message}`);
// If this was the last attempt, throw the error
9 if (i === retries - 1) throw error;
// Wait before retrying (exponential backoff could be used)
10 await delay(1000);
11 }
12 }
13}
14
// Simple delay helper
15function delay(ms) {
16 return new Promise(r => setTimeout(r, ms));
17}
18
// Simulate a failing API that succeeds on 3rd attempt
19let attempts = 0;
20function fakeFetch(url) {
21 return new Promise((resolve, reject) => {
22 attempts++;
// Fail first 2 attempts, succeed on 3rd
23 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 error
28fetchWithRetry("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

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

More JavaScript examples at level 5

← JavaScript typing practice