Sub topic 11
Abort Reasons: AbortError, TimeoutError, and Custom Reasons
An aborted signal tells you two things. signal.aborted says cancellation happened, and signal.reason says why. This chapter covers the second part: which values reason can hold, where they come from, and how your own functions should pass them on so callers get useful errors.
This chapter assumes you know promises and try/catch, and that you have read the earlier chapters on signal.aborted, the abort event, and the cancellable delay() function. All examples run in current browsers and in Node.js 18 or later.
Where a Reason Comes From
A signal gets its reason when it is aborted, and the value depends on what aborted it.
| How the signal was aborted | `signal.reason` | `reason.name` |
|---|---|---|
| `controller.abort()` with no argument | A new `DOMException` | `"AbortError"` |
| `controller.abort(undefined)` | A new `DOMException` | `"AbortError"` |
| `controller.abort(value)` | `value`, exactly as passed | Whatever `value` has |
| `AbortSignal.timeout(ms)` after `ms` elapses | A new `DOMException` | `"TimeoutError"` |
| `AbortSignal.abort(value)` | `value`, or an `AbortError` if omitted | Depends on `value` |
| `AbortSignal.any([...])` | The reason of the first input signal to abort | Inherited |
DOMException is the platform's standard error type for web APIs. In browsers and in Node.js 17 and later, DOMException instances are instanceof Error, so they have a message, a name, and usually a stack trace.
The Default: AbortError
When nobody supplies a reason, the platform creates one:
const controller = new AbortController();
controller.abort();
const { reason } = controller.signal;
console.log(reason instanceof DOMException); // true
console.log(reason instanceof Error); // true
console.log(reason.name); // "AbortError"
console.log(reason.message); // wording varies by runtimeCheck reason.name. Don't check reason.message. Chrome, Firefox, and Node.js use different message text. Don't check reason.code either: the numeric codes on DOMException (20 for abort, 23 for timeout) are legacy, and custom reasons won't have them.
"AbortError" is the convention the whole platform uses for "the caller cancelled this." Calling code across the ecosystem tests err.name === 'AbortError' to decide whether to show an error message or stay quiet.
TimeoutError: Cancelled by a Deadline
AbortSignal.timeout(ms) returns a signal that aborts on its own after ms milliseconds. Its reason has a different name:
const signal = AbortSignal.timeout(50);
signal.addEventListener('abort', () => {
console.log(signal.reason.name); // "TimeoutError"
}, { once: true });The name is different because the meaning is different. An AbortError means someone decided to stop. A TimeoutError means the work took too long, which often counts as a failure worth reporting or retrying. A later chapter shows how to build deadlines with this API. For now, remember that a cancelled operation does not always reject with AbortError, so code that only checks for that name will treat timeouts as unexpected errors.
Custom Reasons
You can pass any value to abort(), and the signal stores that exact object:
const controller = new AbortController();
const why = new Error('User navigated away');
controller.abort(why);
console.log(controller.signal.reason === why); // true
try {
controller.signal.throwIfAborted();
} catch (err) {
console.log(err === why); // true
console.log(err.message); // "User navigated away"
}Custom reasons let the code that aborts tell the code that catches the error why it happened: the user navigated away, a newer search replaced this one, the component unmounted.
The reason is set once
The first abort wins. Later calls to abort() do nothing, and that includes calls with a different reason:
const controller = new AbortController();
controller.abort(new Error('first'));
controller.abort(new Error('second'));
console.log(controller.signal.reason.message); // "first"If two parts of your program can abort the same controller, only the first one's reason will reach the caller.
Choosing what to pass
Any value is allowed, but some choices cause problems later.
| Reason value | `err.name` in the catch | Stack trace | Matches `AbortError` checks |
|---|---|---|---|
| None (default) | `"AbortError"` | Yes | Yes |
| `new DOMException(msg, 'AbortError')` | `"AbortError"` | Yes | Yes |
| `new Error(msg)` | `"Error"` | Yes | No |
| Error subclass with its own `name` | That name | Yes | Only if the name is `"AbortError"` |
| A string, such as `'stop'` | `undefined` | No | No, and `err.name` reads `undefined` |
| `null` | Throws `TypeError` on `err.name` | No | No, and the catch block crashes |
abort(undefined) falls back to the default AbortError. abort(null) does not: the reason really is null. A catch block that reads err.name then throws a TypeError from inside your error handler.
If you want a custom message but still want callers to treat it as ordinary cancellation, keep the name "AbortError":
const controller = new AbortController();
controller.abort(new DOMException('Search superseded by a newer query', 'AbortError'));
console.log(controller.signal.reason.name); // "AbortError"
console.log(controller.signal.reason.message); // "Search superseded by a newer query"If the reason needs its own category so callers handle it differently, use an Error subclass with a distinct name and a little extra data:
class SupersededError extends Error {
constructor(newerQuery) {
super(`Superseded by query "${newerQuery}"`);
this.name = 'SupersededError';
this.newerQuery = newerQuery;
}
}
const controller = new AbortController();
controller.abort(new SupersededError('cats'));
const err = controller.signal.reason;
console.log(err instanceof SupersededError); // true
console.log(err.newerQuery); // "cats"A distinct name gives you precision, but generic code that checks only for AbortError will treat this reason as a real failure. Choose it only when callers actually need to tell the cases apart.
Your Functions Must Propagate the Reason
Once a reason exists, the job of a cancellable function is to reject with that value, unchanged. The delay() from an earlier chapter does this with reject(signal.reason). A common mistake is to invent a new error instead:
// Wrong: throws away the reason the caller chose
function delayBad(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(new Error('Aborted'));
return;
}
const timerId = setTimeout(resolve, ms);
signal?.addEventListener('abort', () => {
clearTimeout(timerId);
reject(new Error('Aborted'));
}, { once: true });
});
}
const controller = new AbortController();
controller.abort(new DOMException('Too slow', 'TimeoutError'));
delayBad(1000, { signal: controller.signal })
.catch((err) => console.log(err.name)); // "Error" — the TimeoutError is lostThe caller can no longer tell a timeout from a user cancellation, and an ordinary AbortError check fails too. Rejecting with signal.reason (or calling signal.throwIfAborted()) fixes both problems and matches the built-in APIs. Modern fetch rejects with signal.reason as well, so a reason passed to abort() comes out of fetch unchanged.
If you need to add context while an error passes through your code, wrap it with cause instead of replacing it:
async function loadProfile(id, { signal } = {}) {
try {
const response = await fetch(`/api/profiles/${id}`, { signal });
return await response.json();
} catch (err) {
if (signal?.aborted && err === signal.reason) {
throw err; // cancellation: pass it through untouched
}
throw new Error(`Could not load profile ${id}`, { cause: err });
}
}Cancellation passes through untouched. Real failures get a clearer message, and the original error stays available as err.cause.
Quick Reference for Classifying Reasons
The next chapter covers caller-side handling in full. This small helper shows the three outcomes your reasons should make easy to tell apart:
function classify(err, signal) {
if (err?.name === 'TimeoutError') return 'timeout';
if (err?.name === 'AbortError') return 'cancelled';
if (signal?.aborted && err === signal.reason) return 'cancelled (custom reason)';
return 'failure';
}
const c = new AbortController();
c.abort(new Error('User navigated away'));
console.log(classify(c.signal.reason, c.signal)); // "cancelled (custom reason)"
console.log(classify(new TypeError('bad JSON'))); // "failure"Comparing err === signal.reason is the most reliable check because it works for any reason, whatever its name.
Exercise
A function runs controller.abort(null) and later a caller's catch block runs if (err.name === 'AbortError') return;. What happens, and how should the aborting code be changed?
Show answer
The signal's reason is null, so the function rejects with null. Reading err.name throws a TypeError inside the catch block, and that TypeError replaces the original rejection. Abort with no argument, or with a real error such as new DOMException('Cancelled', 'AbortError'), so err.name exists and equals "AbortError".
Exercise
Code calls controller.abort(new Error('timeout')) and then controller.abort(). What is controller.signal.reason.name, and why?
Show answer
It is "Error". The first abort sets the reason, and later calls to abort() are ignored, so the reason stays the Error created by the first call and is never replaced by a default AbortError.
Exercise
Rewrite the abort listener in delayBad so that it keeps the caller's reason, and say what else in delayBad should change for the same reason.
Show answer
The listener should call reject(signal.reason) after clearing the timer, instead of reject(new Error('Aborted')). The early check at the top should also call reject(signal.reason) (or call signal.throwIfAborted() inside a try block and reject with the caught error), so pre-aborted signals keep their reason too.