TSTypeScript

TypeScript: Error handling – code examples

Contents

try / catch / finally

Error handling#try#catch#unknown#errorCompare in all languages
Use case: Guard user input or network responses without the program crashing.
try {
  JSON.parse("{kaputt");
} catch (e: unknown) {
  if (e instanceof Error) {
    console.log("Invalid:", e.name);
  }
} finally {
  console.log("Cleaning up");
}

In catch the error is unknown (with strict) because in JavaScript anything can be thrown – so check instanceof Error. As an analogue to int("abc"), JSON.parse with invalid text is used.

Validating external data (unknown)

Error handling#unknown#validation#json#type guard
Use case: Safely turn JSON from files, APIs or forms into typed objects.
interface Nutzer {
  name: string;
  alter: number;
}
function istNutzer(x: unknown): x is Nutzer {
  if (typeof x !== "object" || x === null) return false;
  const o = x as Record<string, unknown>;
  return typeof o.name === "string" && typeof o.alter === "number";
}

const roh: unknown = JSON.parse('{"name":"Ada","alter":36}');
if (istNutzer(roh)) {
  console.log(roh.name.toUpperCase(), roh.alter + 1);
} else {
  console.log("Invalid data");
}

JSON.parse returns any; stored as unknown it forces you to check. With many fields a library such as Zod does the work.

Result type instead of exceptions

Error handling#result#union#error
Use case: Show expected errors (validation, parsing) explicitly in the return type.
type Ergebnis<T, E = string> =
  | { ok: true; wert: T }
  | { ok: false; fehler: E };

function teile(a: number, b: number): Ergebnis<number> {
  return b === 0
    ? { ok: false, fehler: "Division by zero" }
    : { ok: true, wert: a / b };
}

const e = teile(10, 0);
if (e.ok) console.log(e.wert);
else console.log("Error:", e.fehler);

You may only access e.wert after checking e.ok. The caller cannot accidentally ignore the error case.