Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Errors & cleanup

Recognize results and ignored values

TypeScript

Thrown failures use try/catch; await makes a rejected Promise throw here. Numeric conversion often returns NaN instead of throwing. void discards a value.

Fragment

Fragment inside a function.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
try {
  throw new Error("unavailable");
} catch (error) {
  console.error(String(error));
}

Return or propagate a failure

TypeScript

throw exits until caught. With strict checking, a caught value is unknown and need not be an Error. An awaited rejected Promise throws at the await point. A type annotation does not make exceptions part of the return type.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
function requirePositive(n: number): number {
  if (n <= 0) {
    throw new Error("positive value required");
  }
  return n;
}

Recognize resource cleanup

TypeScript

finally runs when leaving a try through ordinary completion, return or a thrown exception. Use it for the cleanup the API requires. Garbage collection does not guarantee timely release of external resources.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let finished = false;

try {
  // Work that may throw.
} finally {
  finished = true;
}

Choose an error-handling strategy: exceptions, error values, Result, error codes, optional, panics

TypeScript

TypeScript inherits JavaScript's model: failures are thrown and caught with try/catch, and a rejected promise throws at the await. Exceptions are invisible in function types, so nothing tells a caller which calls can fail or with what; catch receives unknown. The alternatives are conventions you build yourself: return a discriminated union such as { ok: true, value } | { ok: false, error }, return undefined or null for "not found", or use a library Result type. There are no error codes beyond fields you add (Node.js system errors carry code: 'ENOENT' and so on), and no separate panic mechanism: a bug is an exception nobody catches.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// 1. Exceptions (idiomatic): the signature says number, and failure travels by throw.
function parsePortOrThrow(text: string): number {
  const port = Number(text);
  if (!Number.isInteger(port) || port < 1 || port > 65_535) {
    throw new RangeError(`invalid port: ${JSON.stringify(text)}`);
  }
  return port;
}

// 2. Errors as values (alternative): failure is visible in the return type.
type PortResult = { ok: true; value: number } | { ok: false; error: string };

function parsePort(text: string): PortResult {
  try {
    return { ok: true, value: parsePortOrThrow(text) };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  }
}

// 3. Absence is not an error: undefined means "no such entry".
const wellKnown = new Map([
  ['http', 80],
  ['https', 443]
]);
const lookupPort = (name: string): number | undefined => wellKnown.get(name);

// Exceptions: the caller has to know to catch, and catch receives unknown.
try {
  parsePortOrThrow('99999');
} catch (error) {
  if (!(error instanceof RangeError)) throw error; // rethrow what we do not handle
  console.log('caught:', error.message);
}

// Result values: the compiler makes the caller check ok before reading value.
const result = parsePort('8080');
if (result.ok) console.log('parsed:', result.value);
else console.log('failed:', result.error);

// Optional values: ?? supplies a default; nothing went wrong.
console.log('ssh port:', lookupPort('ssh') ?? 'unknown');

// A bug is not a recoverable error: assert the invariant and let it crash if broken.
const port = lookupPort('https');
assert.ok(port !== undefined, 'https is always in the table');
console.log('https port:', port);

Trade-offs: exceptions cost nothing to write and propagate automatically, but are easy to forget and hard to type. Result unions show failure in the signature and force a check, at the price of explicit plumbing at every call.

In practice: throw for unexpected or environmental failures (I/O, broken invariants); return a union for expected, domain-level outcomes the caller must decide on (validation, "already exists"); return undefined for plain absence. Catch narrowly, check with instanceof, and rethrow what you do not handle.

A function that returns a Result union can still throw: JSON.parse, property access on undefined and library calls inside it all throw normally. Results narrow what callers must check; they do not remove exceptions.

Any value can be thrown, not only Error instances. Throw Error (or a subclass) so there is a stack trace and a message.

neverthrow 8.2.0 and Effect 4.1.2 are popular libraries that add typed Result and effect types; the union shown here needs no dependency.

Define a custom error type: Error subclasses, error structs, error enums, exception hierarchies

TypeScript

A custom error is a class that extends Error. Add fields the caller can branch on: a stable code string, the field or resource involved. Set name so stack traces and String(error) show the subclass, and pass { cause } through to super so the original failure is kept. Callers narrow the unknown value in catch with instanceof, which then types the extra fields.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A base class gives every application error a stable, machine-readable code.
class AppError extends Error {
  readonly code: string;
  constructor(code: string, message: string, options?: ErrorOptions) {
    super(message, options); // options.cause is stored on this.cause
    this.code = code;
  }
}

class NotFoundError extends AppError {
  override name = 'NotFoundError'; // shows up in stack traces and String(error)
  readonly resource: string;
  readonly id: string;
  constructor(resource: string, id: string) {
    super('E_NOT_FOUND', `${resource} ${id} not found`);
    this.resource = resource;
    this.id = id;
  }
}

class ValidationError extends AppError {
  override name = 'ValidationError';
  readonly field: string;
  constructor(field: string, message: string, options?: ErrorOptions) {
    super('E_VALIDATION', message, options);
    this.field = field;
  }
}

// Parse strictly: Number() and BigInt() also accept "0x10", " 7 " and "".
function parseInteger(text: string): number {
  if (!/^-?\d+$/.test(text)) throw new SyntaxError(`not an integer: ${JSON.stringify(text)}`);
  const n = Number(text);
  if (!Number.isSafeInteger(n)) throw new RangeError(`${text} is too large`);
  return n;
}

function parseQuantity(field: string, text: string): number {
  try {
    const n = parseInteger(text);
    if (n < 1 || n > 1000) throw new RangeError(`${n} is outside 1..1000`);
    return n;
  } catch (cause) {
    throw new ValidationError(field, `${field} must be an integer from 1 to 1000`, { cause });
  }
}

function findUser(id: string): { id: string; name: string } {
  if (id !== 'u1') throw new NotFoundError('user', id);
  return { id, name: 'Ada' };
}

const attempts: Array<() => unknown> = [
  () => findUser('u1'),
  () => findUser('u9'),
  () => parseQuantity('quantity', '12.5'),
  () => parseQuantity('quantity', '0x10'),
  () => parseQuantity('quantity', '7')
];

for (const attempt of attempts) {
  try {
    console.log('ok:', attempt());
  } catch (error) {
    // instanceof narrows unknown to the subclass, so its fields are typed.
    if (error instanceof NotFoundError) {
      console.log(`${error.name} [${error.code}] resource=${error.resource} id=${error.id}`);
    } else if (error instanceof ValidationError) {
      const cause = error.cause instanceof Error ? error.cause.message : String(error.cause);
      console.log(`${error.name} [${error.code}] field=${error.field}: ${error.message}`);
      console.log(`  cause: ${cause}`);
    } else {
      throw error;
    }
  }
}

In practice: keep a small hierarchy (one base class with a code, a few subclasses for outcomes callers treat differently). Branch on instanceof or code, never on message text. If errors cross a process or network boundary, instanceof no longer works; serialize the code and check that instead.

instanceof fails across realms (iframes, vm contexts) and between two copies of the same package in node_modules. A code field survives both, and Error.isError(value) (ES2026, Node.js 24+) tells whether a value is a genuine Error from any realm.

ErrorOptions and cause need lib es2022 or later in tsconfig. With older compile targets (ES5), subclassing Error breaks instanceof unless you call Object.setPrototypeOf(this, new.target.prototype).

Parameter properties (constructor(readonly code: string)) are not erasable syntax, so Node.js type stripping and the erasableSyntaxOnly option reject them; declare the fields explicitly as shown.

Add context to an error: cause, %w, source chains, nested exceptions

TypeScript

new Error(message, { cause }) (ES2022) creates a new error that says what this layer was doing and keeps the original as error.cause. Catch, wrap, and rethrow at each layer that has useful context to add; the result is a chain you can walk to print or inspect. cause is typed unknown, because anything can be thrown, so check instanceof Error before reading it.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { readFileSync } from 'node:fs';

function readSettings(path: string): string {
  try {
    return readFileSync(path, 'utf8');
  } catch (cause) {
    // Add what this layer was doing; keep the original as cause.
    throw new Error(`read settings from ${path}`, { cause });
  }
}

function loadConfig(): unknown {
  try {
    return JSON.parse(readSettings('/no/such/dir/settings.json'));
  } catch (cause) {
    throw new Error('load config', { cause });
  }
}

// Walk the cause chain. cause is typed unknown, so check before reading fields.
function* causes(error: unknown): Generator<unknown> {
  for (let current = error; current !== undefined; ) {
    yield current;
    current = current instanceof Error ? current.cause : undefined;
  }
}

// Find the first cause with a Node.js error code such as ENOENT.
function errorCode(error: unknown): string | undefined {
  for (const e of causes(error)) {
    if (e instanceof Error && 'code' in e && typeof e.code === 'string') return e.code;
  }
  return undefined;
}

try {
  loadConfig();
} catch (error) {
  const messages = [...causes(error)].map((e) => (e instanceof Error ? e.message : String(e)));
  console.log(messages.join('\n  caused by: '));
  console.log('root code:', errorCode(error));
}

In practice: wrap where you know something the low-level error does not (which file, which user, which step), and keep messages short; the chain supplies the rest. Search the chain for a code (ENOENT) or a known subclass rather than parsing the outer message. Node.js and browsers print causes in uncaught error output.

cause is only set when the options object has a cause property; new Error(msg, { cause: undefined }) sets it to undefined explicitly, which still shows up as an own property.

Do not wrap and also log at every layer; wrap on the way up and log once where the error is finally handled.

A cause may come from another realm (a vm context, a worker message) where instanceof Error is false. Error.isError(value) (ES2026, Node.js 24+) recognizes those too.

Return typed errors: Result, (T, error), Result<T, E>, std::expected

TypeScript

TypeScript has no built-in Result, but discriminated unions make one in two lines: { ok: true; value: T } | { ok: false; error: E }. Checking r.ok narrows to the right branch, so value cannot be read without the check. Make the error a union too, with a kind tag and per-kind data; a switch on kind with a never assignment in the default fails to compile when someone adds a kind and forgets to handle it. Small helpers (ok, err, andThen) keep the plumbing short.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A Result is a discriminated union: `ok` is the tag the compiler narrows on.
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };

const ok = <T>(value: T): Result<T, never> => ({ ok: true, value });
const err = <E>(error: E): Result<never, E> => ({ ok: false, error });

// The error itself is a union too, so each failure carries its own data.
type UsernameError =
  | { kind: 'empty' }
  | { kind: 'too-long'; max: number; actual: number }
  | { kind: 'bad-char'; char: string };

function parseUsername(input: string): Result<string, UsernameError> {
  const name = input.trim().toLowerCase();
  if (name === '') return err({ kind: 'empty' });
  if (name.length > 16) return err({ kind: 'too-long', max: 16, actual: name.length });
  const bad = [...name].find((c) => !/[a-z0-9_]/.test(c));
  if (bad !== undefined) return err({ kind: 'bad-char', char: bad });
  return ok(name);
}

// Chaining: run the next step only on success, passing errors through unchanged.
function andThen<T, U, E>(r: Result<T, E>, f: (value: T) => Result<U, E>): Result<U, E> {
  return r.ok ? f(r.value) : r;
}

const reserved = new Set(['admin', 'root']);
const notReserved = (name: string): Result<string, UsernameError | { kind: 'reserved' }> =>
  reserved.has(name) ? err({ kind: 'reserved' }) : ok(name);

// Exhaustive switch: if a new kind is added, the `never` assignment stops compiling.
function message(e: UsernameError | { kind: 'reserved' }): string {
  switch (e.kind) {
    case 'empty':
      return 'enter a username';
    case 'too-long':
      return `use at most ${e.max} characters (got ${e.actual})`;
    case 'bad-char':
      return `${JSON.stringify(e.char)} is not allowed`;
    case 'reserved':
      return 'that name is reserved';
    default: {
      const unreachable: never = e;
      return unreachable;
    }
  }
}

for (const input of ['  Ada_L ', '', 'grace hopper', 'x'.repeat(20), 'Admin']) {
  const r = andThen(parseUsername(input), notReserved);
  console.log(JSON.stringify(input), '->', r.ok ? `ok ${r.value}` : `error: ${message(r.error)}`);
}

In practice: use Result unions for expected, domain-level failures the caller must handle (validation, "not found", "reserved name"), and keep throwing for bugs and environmental failures. Keep error kinds as plain data so they serialize, log and test easily.

Wrapping every function in a Result spreads plumbing through the codebase. Draw the line at module boundaries and expected outcomes.

neverthrow 8.2.0 provides Result and ResultAsync classes with map, andThen and match; Effect 4.1.2 goes further with typed errors in its Effect type. Both are dependencies; the union here is not.

If the error union is ever widened to string, the never check stops helping. Keep kind a union of literals.

Crash on a bug (panic): uncaught exceptions, panic/recover, panic!, std::terminate

TypeScript

JavaScript has no separate panic mechanism. An exception that nobody catches, or a rejected promise nobody handles, ends the Node.js process with exit code 1 and a stack trace (unhandled rejections do so by default since Node.js 15). node:assert throws AssertionError, which is just another uncaught exception. process.on('uncaughtException') can log a fatal error, but the process is in an unknown state at that point and should exit.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';

// An assertion states an invariant. If it fails, the program has a bug.
function applyDiscount(cents: number, percent: number): number {
  assert.ok(percent >= 0 && percent <= 100, `percent out of range: ${percent}`);
  return Math.round((cents * (100 - percent)) / 100);
}
console.log('discounted:', applyDiscount(1_000, 15));

// Run a snippet in a child Node.js process and report how that process ended.
function run(label: string, source: string): void {
  const child = spawnSync(process.execPath, ['--eval', source], { encoding: 'utf8' });
  const firstLine = child.stderr.split('\n').find((line) => /^\w*Error\b/.test(line)) ?? '';
  console.log(`${label}: exit ${child.status} ${firstLine.trim()}`);
}

// An exception nobody catches ends the process with exit code 1 and a stack trace.
run('uncaught throw', 'throw new Error("config missing")');

// So does an unhandled promise rejection (the default since Node.js 15).
run('unhandled rejection', 'Promise.reject(new Error("db down"))');

// A failed assertion is just an uncaught AssertionError.
run('failed assertion', 'require("node:assert").ok(1 > 2, "math is broken")');

// A last-resort handler may log, but must still exit: state is unknown after an uncaught error.
run(
  'uncaughtException handler',
  `process.on("uncaughtException", (e) => {
     console.error("Error logged before exit:", e.message);
     process.exit(70);
   });
   throw new Error("bug");`
);

When to crash: when an invariant is broken (a bug), when startup configuration is missing, or when state may be corrupt. Do not catch everything to keep a process alive; let it exit and have a supervisor (systemd, Kubernetes, a process manager) restart it. In a server, catch per request at the framework boundary so one bad request becomes a 500, not a crash.

Resuming normal work after uncaughtException is unsafe: half-finished operations, open transactions and locks are left as they were. Log, flush and exit.

In browsers an uncaught error does not stop the page; it fires the error or unhandledrejection event on window and the next event handler still runs.

process.exitCode = 1 sets the status but lets pending work finish; process.exit(1) stops immediately and can drop buffered output written to a pipe.

Collect several errors: AggregateError, errors.Join, partition, a vector of errors

TypeScript

AggregateError (ES2021) wraps several errors in one: new AggregateError(errors, message), with the list on error.errors. Promise.any rejects with one when every promise fails. For concurrent work, Promise.allSettled waits for every promise and returns { status: 'fulfilled', value } or { status: 'rejected', reason } for each, so you can keep the successes and gather the failures; Promise.all instead rejects on the first failure.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Signup = { email: string; age: string; country: string };

class FieldError extends Error {
  override name = 'FieldError';
  readonly field: string;
  constructor(field: string, message: string) {
    super(`${field}: ${message}`);
    this.field = field;
  }
}

// Validate every field and report all problems at once, instead of stopping at the first.
function validate(form: Signup): void {
  const errors: FieldError[] = [];
  if (!form.email.includes('@')) errors.push(new FieldError('email', 'must contain @'));
  const age = Number(form.age);
  if (!Number.isInteger(age) || age < 13) errors.push(new FieldError('age', 'must be 13 or older'));
  if (form.country.length !== 2) errors.push(new FieldError('country', 'use a 2-letter code'));
  if (errors.length > 0) throw new AggregateError(errors, `${errors.length} invalid fields`);
}

try {
  validate({ email: 'ada.example.com', age: '9', country: 'GB' });
} catch (error) {
  if (!(error instanceof AggregateError)) throw error;
  console.log(error.message);
  for (const e of error.errors) console.log('  -', e instanceof Error ? e.message : String(e));
}

// Concurrent work: allSettled waits for everything and keeps each outcome.
async function fetchPrice(sku: string): Promise<number> {
  await new Promise((resolve) => setTimeout(resolve, 5));
  if (sku.startsWith('x')) throw new Error(`no price for ${sku}`);
  return sku.length * 100;
}

async function main(): Promise<void> {
  const skus = ['apple', 'xylo', 'pear', 'xeno'];
  const settled = await Promise.allSettled(skus.map(fetchPrice));

  const prices = settled.flatMap((r, i) =>
    r.status === 'fulfilled' ? [`${skus[i]}=${r.value}`] : []
  );
  const failures = settled.flatMap((r) => (r.status === 'rejected' ? [r.reason] : []));
  console.log('prices:', prices.join(', '));

  // Promise.any rejects with an AggregateError only when every promise fails.
  try {
    await Promise.any(['xa', 'xb'].map(fetchPrice));
  } catch (error) {
    if (error instanceof AggregateError) console.log(`any: all ${error.errors.length} failed`);
  }

  if (failures.length > 0) {
    const all = new AggregateError(failures, `${failures.length} of ${skus.length} lookups failed`);
    console.log(all.message);
  }
}

main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

In practice: for form or config validation, check every field and report all problems together, either as an AggregateError or as a returned array of field errors (often easier for a UI). For batches, use allSettled and decide afterwards whether partial success is acceptable.

AggregateError.errors is typed any[]; check each entry with instanceof before reading fields.

Promise.allSettled does not cancel the remaining work when one fails, and an unbounded list starts every task at once. Limit concurrency for large batches.

Decide where to handle an error: translate at boundaries, log once, retry with backoff

TypeScript

Most code should let errors pass through. Handle an error only where you can do something about it: retry, fall back, translate it, or turn it into a response. Three boundaries matter. At a module boundary (storage, an HTTP client), translate low-level errors (driver codes, socket errors) into domain errors the rest of the program understands, keeping the original as cause. At the top (a request handler, a CLI main), decide the status code and the user-facing message, and log once with a request id. Retries belong next to the call that failed, and only for transient errors.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { setTimeout as sleep } from 'node:timers/promises';

// --- storage layer: errors speak the driver's language ---------------------
class DbError extends Error {
  override name = 'DbError';
  readonly code: 'UNIQUE_VIOLATION' | 'CONNECTION_RESET';
  constructor(code: DbError['code'], message: string) {
    super(message);
    this.code = code;
  }
}

let flakyCalls = 0;
async function insertUser(email: string): Promise<number> {
  if (flakyCalls++ === 0 || email.startsWith('down')) {
    throw new DbError('CONNECTION_RESET', 'socket closed by peer 10.0.3.7');
  }
  if (email === 'ada@example.com') {
    throw new DbError('UNIQUE_VIOLATION', 'duplicate key users_email_key');
  }
  return 42;
}

// --- service layer: translate to domain errors, retry only transient ones ----
class EmailTakenError extends Error {
  override name = 'EmailTakenError';
}

// Capped exponential backoff with full jitter: before retry i, sleep a random time
// in [0, min(capMs, baseMs * 2^i)). The signal cancels the wait (and the retries).
async function withRetry<T>(fn: () => Promise<T>, signal: AbortSignal, attempts = 3): Promise<T> {
  const baseMs = 10;
  const capMs = 200;
  for (let i = 1; ; i++) {
    try {
      return await fn();
    } catch (error) {
      const transient = error instanceof DbError && error.code === 'CONNECTION_RESET';
      if (!transient || i === attempts) throw error; // never retry a permanent failure
      await sleep(Math.random() * Math.min(capMs, baseMs * 2 ** i), undefined, { signal });
    }
  }
}

async function registerUser(email: string, signal: AbortSignal): Promise<number> {
  try {
    return await withRetry(() => insertUser(email), signal);
  } catch (error) {
    if (error instanceof DbError && error.code === 'UNIQUE_VIOLATION') {
      throw new EmailTakenError(`email already registered: ${email}`, { cause: error });
    }
    throw error;
  }
}

// --- handler: the one place that logs and picks the user-facing message -----
async function handleSignup(email: string): Promise<{ status: number; body: string }> {
  try {
    const id = await registerUser(email, AbortSignal.timeout(1_000)); // deadline for all attempts
    return { status: 201, body: `user ${id} created` };
  } catch (error) {
    if (error instanceof EmailTakenError) {
      return { status: 409, body: 'That email is already registered.' }; // expected: no log
    }
    const requestId = 'req-7f3a';
    console.error(`[${requestId}] signup failed`, error); // the whole error: stack and cause
    return { status: 500, body: `Something went wrong (reference ${requestId}).` };
  }
}

async function main(): Promise<void> {
  console.log(await handleSignup('grace@example.com')); // first call is transient, retried
  console.log(await handleSignup('ada@example.com'));
  console.log(await handleSignup('down@example.com')); // transient every time: gives up after 3
}

main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

In practice: never show internal messages (SQL, hostnames, stack traces) to users; give them a short message and a reference id, and put the details in the log. Do not log and rethrow at every layer, which produces the same failure many times. Retry with a limit, capped exponential backoff with jitter and a deadline (an AbortSignal), and never retry validation or "already exists" errors.

Full jitter (a random wait between 0 and the current ceiling) stops many clients that failed together from retrying together. The setTimeout from node:timers/promises rejects with an AbortError when the signal fires, which ends the retries.

Only retry operations that are safe to repeat (idempotent), or the retry may apply a write twice.

Expected outcomes such as 409 Conflict are not errors from the service's point of view; logging them as errors floods alerts.