Sub topic 12
Handling Cancellation in the Caller
This chapter assumes you know try/catch, async/await, and the AbortError and TimeoutError names from the previous chapter. Earlier chapters covered the function side. Here you write the code that calls a cancellable function and decides what a rejection means.
Cancellation Is Not a Failure
If the user clicks "Cancel" and the request stops, the program did what it was asked. Showing an error toast or sending a crash report in that case is a bug. If the network goes down, the caller still needs to report it. A caller's catch block has to tell these outcomes apart:
| Outcome | Typical `err.name` | Usual response |
|---|---|---|
| Caller aborted | `AbortError` | Stay quiet, reset UI state |
| Deadline passed | `TimeoutError` | Tell the user, maybe retry |
| Real failure | `TypeError`, `Error`, etc. | Report or rethrow |
Checking the Error Name
Check err.name, not instanceof DOMException. AbortError is a DOMException, and so are many unrelated errors. The name is the only reliable signal.
const controller = new AbortController();
async function loadUser(id, { signal } = {}) {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`, { signal });
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}
async function showUser(id) {
try {
const user = await loadUser(id, { signal: controller.signal });
console.log('loaded:', user.name);
} catch (err) {
if (err.name === 'AbortError') {
console.log('cancelled by the caller');
return;
}
if (err.name === 'TimeoutError') {
console.log('the request took too long');
return;
}
throw err;
}
}
showUser(1);
controller.abort();The final throw err is the important line. A catch that swallows every error hides real bugs along with cancellations.
When You Passed a Custom Reason
If you call controller.abort(new Error('User navigated away')), the function rejects with that exact error, and its name is Error, not AbortError. A name check alone misses it. You own the controller, so ask the signal directly:
function isMyCancellation(err, signal) {
return signal.aborted && err === signal.reason;
}This check works with any reason, default or custom. It also avoids a subtle mistake. An AbortError that comes from some other signal deeper in the call stack does not mean that you cancelled.
Cleaning Up UI State
Cancellation usually still needs some cleanup, such as hiding a spinner or re-enabling a button. Put that in finally so it runs on every outcome:
async function onSearch(button, signal) {
button.disabled = true;
try {
await loadUser(2, { signal });
} catch (err) {
if (err.name !== 'AbortError') throw err;
} finally {
button.disabled = false;
}
}Common Mistakes
- Logging every rejection as an error, so analytics fill with cancellations.
- Using an empty
catch {}and losing real failures. - Checking
err.messagetext, which differs between browsers and Node. - Treating
TimeoutErrorlikeAbortError, when the user often needs to hear about a timeout.
Exercise
A caller runs controller.abort('stale') and its catch block only checks err.name === 'AbortError'. What happens, and how do you fix it?
Show answer
The function rejects with the string "stale", which has no name property, so the check fails and the caller rethrows or reports it as a failure. The fix is to test controller.signal.aborted && err === controller.signal.reason, which recognizes any abort reason.
Exercise
Why should the caller's catch block end with throw err instead of returning?
Show answer
Errors that are neither cancellations nor timeouts are real failures. Rethrowing them lets higher-level handlers or error reporting see them instead of losing them silently.