Terminology (4)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Failure value
- A failure returned as an ordinary value, such as a Go error or a Rust Err, that the caller must check.
- Exception
- A raised failure that transfers ordinary control toward a matching handler; cleanup may run along that path.
- Swallowed failure
- A failure caught or received and then ignored, so the program carries on as if it had succeeded.
- instanceof check
- Testing which class a caught value belongs to, to tell kinds of failure apart.
How an operation reports failure
A failure representation carries the information a caller needs when an operation cannot produce its normal result. A returned failure travels through ordinary values; an exception transfers control to a matching handler. Handling means choosing the next action, such as refusing one request or stopping the current operation.
TypeScript code can use JavaScript exceptions or return a result object with distinct success and failure cases. The API chooses that representation. Inspect both the returned value and surrounding try/catch to find where the caller makes its decision.
01Two ways to fail
Follow the shown API’s failure route
A clinic dispensary records kit requests. A shortage should identify the affected request without losing later work. Entered quantities can also fail conversion, and a missing item needs a different response from a known item that has run out. The tool must preserve those failure signals until the caller decides what to report.
A small kit starts with 3 units. Each treatment asks take for 2 units and reports completion afterward. Trace the calls for ana and ben, including which caller decides how to report a shortage.
take throws an Error; main wraps both treat calls in try/catch.
function take(kit: { left: number }, count: number): number {
if (count > kit.left) {
throw new Error(`only ${kit.left} left`);
}
kit.left -= count;
return kit.left;
}
function treat(kit: { left: number }, patient: string): void {
take(kit, 2);
console.log(`treated ${patient}`);
}
const kit = { left: 3 };
try {
treat(kit, "ana");
treat(kit, "ben");
console.log("all treated");
} catch (error) {
console.log(`failed: ${(error as Error).message}`);
}
npx tsc main.ts --strict --target ES2022 --module Node16 --moduleResolution Node16 --types node --outDir out && node out/main.js
Save one complete probe in a fresh directory under its selected filename. Use local TypeScript and Node types with the declared ES2022/Node16 CommonJS emit workflow; set package.json’s type field to commonjs, preserving other fields. Rust uses edition 2024. The C++ track uses the shown C++2c compiler profile. Each command is guarded so a failed build is not followed by a stale executable.
02The trap
Each way of reporting a failure has its own way of losing it
A caller requests 5 units from a kit of 3. Inspect what the following report does with the operation’s failure signal before predicting its line.
The call is inside try with an empty catch.
function take(kit: { left: number }, count: number): void {
if (count > kit.left) {
throw new Error(`only ${kit.left} left`);
}
kit.left -= count;
}
const kit = { left: 3 };
try {
take(kit, 5);
} catch {
// nothing to do here
}
console.log(`gave 5, left ${kit.left}`);
03Converting
Observe a checked conversion from a failure value
The import path for quantity words will need to decide whether conversion failure is reportable data or a reason to stop. This reduced probe takes 2 units from 3, then asks for 2 from the remaining 1. Inspect the operation that extracts a value from each result.
take returns a result object; inspect how mustTake selects a numeric result.
type Taken = { ok: true; left: number } | { ok: false; message: string };
function take(left: number, count: number): Taken {
return count > left
? { ok: false, message: `only ${left} left` }
: { ok: true, left: left - count };
}
function mustTake(left: number, count: number): number {
const result = take(left, count);
if (!result.ok) throw new Error(result.message);
return result.left;
}
console.log(mustTake(3, 2));
console.log(mustTake(1, 2));
04Repair the dispensary
Keep serving, reject bad quantities, tell failures apart
The dispensary needs to keep processing after a refused request, report failed quantity conversions and distinguish an absent item from exhausted stock. Each supplied complete file carries the relevant reader and working support operations.
Repair the dispensary
Continue the request list, preserve conversion failures and reconcile two expected stock failures.
In the frontend Keep failure status beside its display data. Optional
A component can receive an operation’s outcome as a value. Zero remaining units can be a successful result; a failure carries a message. Render using the explicit status so the display does not turn a failure into a plausible numeric default.
type Outcome =
| { ok: true; remaining: number }
| { ok: false; message: string };
export default function KitOutcome({ outcome }: { outcome: Outcome }) {
return outcome.ok
? <p>{outcome.remaining} units left</p>
: <p role="status">{outcome.message}</p>;
}
The component receives the result; it does not catch a throwing operation. An ok result with remaining 0 renders 0 units left, while a failed result renders its message.
Sources: React conditional rendering,Svelte if blocks,Svelte props.
Sign in to keep your read marks on every device. Sign in
Was this helpful?