AbortError and throwIfAborted
AbortError
Section titled “AbortError”type AbortReason = 'timeout' | 'client-disconnected';
class AbortError extends Error { name: 'AbortError'; readonly reason?: AbortReason; constructor(message = 'Operation was aborted', reason?: AbortReason);}The middleware aborts the signal with an AbortError as signal.reason. fetch rejects with the signal’s reason
as is, and so do signal.throwIfAborted() and throwIfAborted() below, so error instanceof AbortError and
error.reason work on what they throw.
try { return await fetch(url, { signal }).then((r) => r.json());} catch (error) { if (error instanceof AbortError) { this.logger.log(`stopped: ${error.reason}`); // 'timeout' | 'client-disconnected' } throw error;}throwIfAborted(signal, message?)
Section titled “throwIfAborted(signal, message?)”A checkpoint for code that does not take a signal: loops, CPU work, sequences of calls.
for (const file of files) { throwIfAborted(signal); await this.convert(file);}- Not aborted: returns.
- Aborted by the middleware, no
message: rethrows the middleware’sAbortErroritself (same object, samereason). - Aborted, with a
message: throws a newAbortError(message, reason)that keeps the reason. - Aborted with some other reason (you called
controller.abort(x)yourself): throwsnew AbortError(message)without a reason.
The native signal.throwIfAborted() works too; it throws signal.reason as is.