Docs

16.2-Advanced-Error-Handling

18.2 Advanced Error Handling

Overview

Proper error handling in asynchronous code is crucial for building robust applications. This section covers advanced patterns for handling errors in async operations.

Error Propagation in Async Code

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│                     Async Error Propagation                             │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│                                                                         │
│  // Promises - errors propagate through chain                           │
│  fetchUser()                                                            │
│      .then(processUser)     // Error here...                            │
│      .then(saveUser)        // ...skips this...                         │
│      .then(notifyUser)      // ...and this...                           │
│      .catch(handleError);   // ...caught here!                          │
│                                                                         │
│  // Async/await - use try/catch                                         │
│  async function doWork() {                                              │
│      try {                                                              │
│          const user = await fetchUser();                                │
│          const processed = await processUser(user);                     │
│          await saveUser(processed);                                     │
│      } catch (error) {                                                  │
│          // Any error from above caught here                            │
│      }                                                                  │
│  }                                                                      │
│                                                                         │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Error Types in Async Code

Error TypeDescriptionExample
Network ErrorFailed requestsFetch failed
Timeout ErrorOperation too slowRequest timeout
Validation ErrorInvalid dataBad JSON
Auth ErrorPermission denied401 Unauthorized
Rate Limit ErrorToo many requests429 Too Many Requests

Error Handling Patterns

1. Try-Catch with Async/Await

async function fetchData() {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    console.error('Fetch failed:', error);
    throw error; // Re-throw or handle
  }
}

2. Catch at Multiple Levels

async function process() {
  try {
    const data = await fetchData();
    try {
      await saveData(data);
    } catch (saveError) {
      // Handle save-specific errors
      await handleSaveFailure(data);
    }
  } catch (fetchError) {
    // Handle fetch errors
  }
}

3. Error Recovery

async function fetchWithFallback() {
  try {
    return await fetchPrimary();
  } catch {
    console.log('Primary failed, trying fallback...');
    return await fetchFallback();
  }
}

Global Error Handlers

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│                    Global Error Handlers                                │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│                                                                         │
│  // Unhandled Promise Rejections (Node.js/Browser)                      │
│  window.addEventListener('unhandledrejection', event => {               │
│      console.error('Unhandled rejection:', event.reason);               │
│      event.preventDefault();  // Prevent default logging                │
│  });                                                                    │
│                                                                         │
│  // Node.js specific                                                    │
│  process.on('unhandledRejection', (reason, promise) => {                │
│      console.error('Unhandled Rejection at:', promise);                 │
│  });                                                                    │
│                                                                         │
│  // General errors                                                      │
│  window.onerror = function(msg, url, line, col, error) {                │
│      console.error('Error:', msg);                                      │
│      return true;  // Prevent default                                   │
│  };                                                                     │
│                                                                         │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Custom Error Classes

class NetworkError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.name = 'NetworkError';
    this.statusCode = statusCode;
  }
}

class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}

Summary

  • •Always handle async errors
  • •Use try/catch with async/await
  • •Create custom error types
  • •Set up global handlers as safety net
  • •Log errors for debugging
  • •Provide meaningful error messages
.2 Advanced Error Handling - JavaScript Tutorial | DeepML