A caller may need to know which task failed as well as why it failed. Extend Error to introduce a recognizable TaskError carrying an index and the original cause. The second Error constructor argument accepts an options object with cause in the environments used by this course.
Keep messages useful for people and explicit properties useful for code. Do not ask callers to parse an index back out of an English message. instanceof TaskError works for instances from this class in the same realm; serializing an error to JSON or crossing a realm does not preserve every identity assumption.
A thrown value may be undefined, null or text. Store an explicit failed flag instead of testing whether the stored error is truthy. Likewise, preserve the first observed failure rather than overwriting it every time another cancelled callback rejects. This policy is about observation order, not guaranteeing which physical operation failed first.
Read the subclass constructor
class TaskError extends Error makes TaskError a subclass of Error: an instance is also an Error. Inside its constructor, super(message, options) calls the Error constructor to initialize the message and cause. Call it before accessing this; then add the task-specific index and name. Here cause is the original failure value, not necessarily another Error.
Follow the example in three steps: initialize the Error part with super, store the index on this instance, then inspect the instance in the caller. You do not need a general inheritance hierarchy to use this one specialized error. See the extends reference for the language rule.
Predict, run, and explain
Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.
class TaskError extends Error {
constructor(index, cause) {
super(`Task ${index} failed`, { cause });
this.name = "TaskError";
this.index = index;
}
}
const error = new TaskError(2, new Error("offline"));
console.log(error instanceof Error);
console.log(error.index, error.cause.message);Check your prediction
true
2 offlinePreserve machine-readable failure information
An error message helps a person, while explicit properties let code inspect a failure without parsing English text. Preserve an original cause rather than replacing it with an unrelated message. A task index and cause describe a different failure boundary from an input iterator error.
Not every thrown value is an Error instance. Undefined and null are still legal failures. Track whether failure occurred with a separate flag so a falsy reason cannot accidentally turn rejection into success.
class TaskError extends Error {
constructor(index, cause) {
super(`Task ${index} failed`, { cause });
this.index = index;
}
}
const original = new Error("offline");
const wrapped = new TaskError(2, original);
console.log(wrapped.index);
console.log(wrapped.cause === original);
console.log(wrapped instanceof Error);Check your prediction
2
true
trueThe original object survives wrapping by identity. Callers can inspect cause and index separately; changing message wording should not break those callers.
let failed = false;
let reason;
try {
throw undefined;
} catch (error) {
failed = true;
reason = error;
}
console.log(failed);
console.log(Boolean(reason));Check your prediction
true
falseA truthiness check on reason would misclassify the outcome. This is why the final pool keeps a failed flag independently of its stored failure value.
Try the rule on new inputs
Test an Error, text, null and undefined as causes. For mapper failure versus source failure, state exactly which one is wrapped and which original value the caller should receive.
Debug a plausible mistake
Repair first-failure selection
The first observed reason must remain undefined, so print true. Test null, 0 and an Error as first reasons afterward. A falsy reason is still a real failure.
Predict the supplied program's actual behavior first. It runs without an error, but breaks the requirement. Make a small repair, then try a case that would distinguish the repaired version from the original.
let failure;
function record(reason) {
if (!failure) {
failure = reason;
}
}
record(undefined);
record(new Error("Later"));
console.log(failure === undefined);Hint 1: the idea
The stored value cannot also serve as the flag indicating that a value was stored.
Hint 2: a first step
Keep an explicit hasFailed flag and set it before storing the first reason.
Show one solution
let failure;
let hasFailed = false;
function record(reason) {
if (!hasFailed) {
hasFailed = true;
failure = reason;
}
}
record(undefined);
record(new Error("Later"));
console.log(failure === undefined);trueThe original printed false. if (!failure) asked whether the stored value was falsy, and undefined is, so the later Error overwrote the first failure. hasFailed records the fact that a failure happened separately from what the failure was, so undefined, null, 0 and "" are all kept as first reasons. A test that only recorded Errors would never notice the difference, which is why the brief asks you to try the falsy cases.
Trace the contract before building
A public failure can need both human text and machine-readable context. Keep the task index as a property rather than requiring callers to extract it from a message. Preserve the original cause so wrapping adds information instead of replacing it.
Observation order is distinct from physical failure time: the library can only select the first failure it observes. Use an explicit flag because every JavaScript value, including falsy values, can be thrown. Test the selection policy with undefined as well as an Error. Otherwise a truthiness check can silently let a later cleanup failure become the reported reason.
Your turn
Wrap the callback, not the source
TaskError is supplied. Write mapAll(values, fn), which calls fn(value, index) for each value and collects the results. When fn throws, rethrow a TaskError carrying that index and the thrown value as its cause, whatever the value is. When reading from values itself throws, let that error through unwrapped: it is not a task's failure. The supplied report uses instanceof to tell the two apart. Print:
ok: 2,4,6
task 1 failed: empty input
source failed: disk
task 0 failed: undefinedclass TaskError extends Error {
constructor(index, cause) {
super(`Task ${index} failed`, { cause });
this.name = "TaskError";
this.index = index;
}
}
function mapAll(values, fn) {
// Wrap only a failure thrown by fn in TaskError(index, cause).
// A failure from the source itself must pass through unchanged.
const results = [];
for (const value of values) {
results.push(fn(value));
}
return results;
}
function report(values, fn) {
try {
return `ok: ${mapAll(values, fn).join(",")}`;
} catch (error) {
if (error instanceof TaskError) {
return `task ${error.index} failed: ${error.cause}`;
}
return `source failed: ${error instanceof Error ? error.message : error}`;
}
}
function* brokenSource() {
yield 1;
throw new Error("disk");
}
console.log(report([1, 2, 3], n => n * 2));
console.log(report(["a", "", "c"], text => {
if (text === "") throw "empty input";
return text.toUpperCase();
}));
console.log(report(brokenSource(), n => n * 2));
console.log(report([1], () => {
throw undefined;
}));Hint 1: the idea
Two different things can throw inside one for...of: the loop asking values for the next item, and your call to fn. Only one of them should be wrapped, so the try must surround only that one.
Hint 2: a first step
Run the starter first: every failure is reported as source failed, including the two thrown by fn. Add an index counter and put try { ... } catch (cause) { ... } around the results.push(fn(value, index)) line only. The second line becomes task 1 failed: empty input, while the third stays source failed: disk.
Show one solution
class TaskError extends Error {
constructor(index, cause) {
super(`Task ${index} failed`, { cause });
this.name = "TaskError";
this.index = index;
}
}
function mapAll(values, fn) {
const results = [];
let index = 0;
for (const value of values) {
try {
results.push(fn(value, index));
} catch (cause) {
throw new TaskError(index, cause);
}
index += 1;
}
return results;
}
function report(values, fn) {
try {
return `ok: ${mapAll(values, fn).join(",")}`;
} catch (error) {
if (error instanceof TaskError) {
return `task ${error.index} failed: ${error.cause}`;
}
return `source failed: ${error instanceof Error ? error.message : error}`;
}
}
function* brokenSource() {
yield 1;
throw new Error("disk");
}
console.log(report([1, 2, 3], n => n * 2));
console.log(report(["a", "", "c"], text => {
if (text === "") throw "empty input";
return text.toUpperCase();
}));
console.log(report(brokenSource(), n => n * 2));
console.log(report([1], () => {
throw undefined;
}));ok: 2,4,6
task 1 failed: empty input
source failed: disk
task 0 failed: undefinedThe try covers only the call to fn, so the error that brokenSource throws while for...of reads from it never enters the catch and reaches report as a plain Error. Wrapping the whole loop instead would label the disk failure as task 1, blaming a task that never ran. cause is passed through as the thrown value itself, so the string "empty input" and even undefined survive. The last line shows that a TaskError is still recognised by instanceof, not by whether its cause is truthy.
Change it and test it
Test undefined as a cause. Create a separate failed flag and demonstrate that throwing undefined still sets it. Explain why testing if(error) cannot represent every thrown value and why a cleanup error should not erase the primary failure.
Completion is saved in this browser only. It does not measure mastery.