Error: The operation was aborted due to timeout (AbortSignal.timeout / TimeoutError)
Quick answer
AbortSignal.timeout(ms) fires an abort after the given duration, which surfaces wherever the signal was passed — most commonly into fetch() — as a TimeoutError (a DOMException). Catch it specifically and check `error.name === 'TimeoutError'` to distinguish it from other abort reasons or network failures.
What causes this error
AbortSignal.timeout(ms) creates a signal that auto-aborts after the specified time — pass it into fetch()'s signal option and the request is cancelled if it runs too long. The resulting rejection is a `DOMException` named `TimeoutError`, which looks similar to other network errors unless you inspect `.name` specifically.
The Fix
try {
const res = await fetch('https://slow-api.example.com/data', {
signal: AbortSignal.timeout(5000), // aborts after 5s
});
} catch (err) {
if (err.name === 'TimeoutError') {
console.error('Request timed out after 5s');
} else if (err.name === 'AbortError') {
console.error('Request was aborted manually');
} else {
console.error('Network error:', err.cause ?? err);
}
}Common causes / variations
- Setting the timeout too aggressively for an endpoint's real-world latency
- Combining a manual `AbortController` with `AbortSignal.timeout()` incorrectly (you need `AbortSignal.any([...])` to merge multiple signals)
- Not distinguishing `TimeoutError` from a generic `fetch failed` network error in error-handling logic
Related errors
See also: TypeError fetch failed ECONNRESET, connect ECONNREFUSED.
Was this fix helpful?
Comments
Loading comments...