Skip to content

CancelError

CancelError is the specific error type thrown when a cancellable operation is cancelled. It extends the standard Error class and carries the cancellation reason.

Cancellation signal Catch CancelError to distinguish cancellation from other errors.

Root package:

import { CancelError } from "@vgerbot/async";

Module subpath:

import { CancelError } from "@vgerbot/async/cancellable";

Leaf subpath:

import { CancelError } from "@vgerbot/async/cancellable/CancelError";
import { cancellable, CancelError } from "@vgerbot/async";
const handle = cancellable(async (token) => {
await token.sleep(5000);
return "done";
});
setTimeout(() => handle.cancel("User navigated away"), 100);
try {
await handle;
} catch (error) {
if (error instanceof CancelError) {
console.log("Cancelled:", error.reason);
} else {
throw error; // Re-throw non-cancellation errors
}
}
class CancelError extends Error {
readonly reason: unknown;
get rawReason(): unknown;
static fromReason(message: string, rawReason: unknown): CancelError;
}
Property Type Description
name string Always "CancelError".
message string Human-readable message.
reason unknown The original reason passed to cancel(). Same as rawReason.
rawReason unknown The raw reason as passed to AbortController.abort(), before any CancelError wrapping.
cause unknown The underlying cause (same as rawReason when created via fromReason).

CancelError.fromReason(message, rawReason)

Section titled “CancelError.fromReason(message, rawReason)”

Creates a CancelError from a message and raw reason. If rawReason is already a CancelError, it is returned as-is.

const error = CancelError.fromReason("Task cancelled", "User cancelled");
console.log(error.message); // "Task cancelled"
console.log(error.reason); // "User cancelled"

Distinguishing cancellation from other errors

Section titled “Distinguishing cancellation from other errors”
try {
await handle;
} catch (error) {
if (error instanceof CancelError) {
// Handle cancellation gracefully
console.log("Operation was cancelled");
} else {
// Re-throw or handle other errors
throw error;
}
}
try {
await handle;
} catch (error) {
if (error instanceof CancelError) {
if (error.reason === "timeout") {
console.log("Operation timed out");
} else if (error.reason === "user_action") {
console.log("User cancelled");
}
}
}

When using executors like PoolTaskExecutor, cancelled tasks reject with CancelError:

import { PoolTaskExecutor, CancelError } from "@vgerbot/async";
const executor = new PoolTaskExecutor(3);
try {
await executor.exec(async (token) => {
await token.sleep(5000);
});
} catch (error) {
if (error instanceof CancelError) {
console.log("Task was cancelled");
}
}

Use instanceof to check for CancelError. This is the recommended pattern.

if (error instanceof CancelError) {
// error.reason is `unknown`
// error.cause is `unknown`
}