Error Handling in JavaScript

From the Fetch API cheat sheet · Response Handling · verified Jul 2026

Error Handling

Comprehensive error handling and retry strategies

javascript
// Basic error handling
try {
  const response = await fetch(url)
  
  if (!response.ok) {
    throw new Error(\`HTTP \${response.status}: \${response.statusText}\`)
  }
  
  const data = await response.json()
} catch (error) {
  if (error instanceof TypeError) {
    console.error('Network error:', error)
  } else {
    console.error('Request failed:', error)
  }
}

// Detailed status handling
const response = await fetch(url)

switch(response.status) {
  case 200:
    return await response.json()
  case 204:
    return null
  case 400:
    throw new Error('Bad request')
  case 401:
    throw new Error('Unauthorized')
  case 404:
    throw new Error('Not found')
  case 500:
    throw new Error('Server error')
  default:
    throw new Error(\`Unexpected status: \${response.status}\`)
}

// Network timeout
try {
  const response = await fetch(url, {
    signal: AbortSignal.timeout(5000)
  })
  return await response.json()
} catch (error) {
  if (error.name === 'TimeoutError') {
    console.error('Request timed out')
  }
}
❌ Fetch only rejects on network errors, not HTTP errors
⚡ Implement exponential backoff for retry delays
💡 Don't retry 4xx client errors, only 5xx server errors
🔴 Always set timeouts to prevent hanging requests

More JavaScript tasks

Back to the full Fetch API cheat sheet