advanced · 24 minute study
Make failure part of the API contract
Loading, unauthorized, invalid input and network failure should lead to deliberate behavior instead of undefined access and fake success.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- A callback must accept everything its caller can send — Function compatibility errors often reveal a real mismatch between who chooses an input and who promises to handle it.
First, build a mental model
A promise describes eventual completion. Its generic type describes the fulfilled value; TypeScript does not encode every possible rejection in Promise<T>. A result union can make expected failures explicit.
- Use a discriminated result for expected domain failures.
- Keep unexpected exceptions visible at an appropriate boundary.
- A catch value is unknown under strict checking; narrow before reading message.
- Cancellation and stale-result rejection are separate from validating a successful payload.
type Result<T> = { ok: true; value: T } | { ok: false; error: 'network' | 'invalid' };
async function readScore(raw: string): Promise<Result<number>> {
try {
const value: unknown = JSON.parse(raw);
return typeof value === 'number' && Number.isFinite(value)
? { ok: true, value } : { ok: false, error: 'invalid' };
} catch { return { ok: false, error: 'invalid' }; }
}
async function show() {
const result = await readScore('12');
return result.ok ? result.value.toFixed(0) : result.error;
}- Await
The fulfilled value is still a union of expected outcomes.
- Discriminate
ok=true establishes value; ok=false establishes error.
- Render
The caller decides how each outcome appears to the learner/user.
Production thinking
Take this beyond the example.
Keep error codes stable and messages useful. Distinguish invalid input, authorization failure, conflict, transient failure and cancellation; retry only when the operation's semantics permit it.
Sources and further reading
Your evidence
unseen is a local learning signal, not a credential or proof of production competence.
Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.
Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.
Next lesson · Design away impossible states →