Course contentsShow
← JavaScript
Lesson 2303 of 2,72347. Networking PrimitivesFree lesson

Handling AbortError

Catch and identify AbortError exceptions thrown when a fetch or operation is aborted.

Handling AbortError

You'll learn how to gracefully catch and identify the specific error thrown when a fetch request is aborted.

When you abort a fetch using an AbortController, the browser doesn't silently stop—it throws a special error called AbortError. This is actually a DOMException with the name "AbortError". If you don't handle it, your error-catching code might treat it like a network failure or server problem, which would be misleading.

Why This Matters

Imagine canceling a search request because the user typed something new. You don't want to show an error message saying "Network failed!"—the cancellation was intentional. You need to distinguish between errors you caused (aborts) and genuine problems.

Catching and Identifying AbortError

Wrap your fetch in a try-catch block and check the error's name property:

const controller = new AbortController();

try {
  const response = await fetch('/api/data', { 
    signal: controller.signal 
  });
  const data = await response.json();
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Fetch was aborted—no problem!');
    // Handle gracefully, maybe do nothing
  } else {
    console.error('Real error occurred:', error);
    // Show user-facing error message
  }
}

Different Treatment for Different Errors

Aborted requests are usually intentional user actions (canceling searches, navigating away). Real errors (network down, 500 responses) need user feedback. By checking error.name === 'AbortError', you can route each scenario appropriately—perhaps logging aborts quietly while displaying alerts for genuine failures.

Key Takeaway: Always check if error.name === 'AbortError' in your catch blocks to distinguish intentional cancellations from real network or server errors.