Updated Nov 29, 2026

10 - Error Handling

📋 Jump to Takeaways

🎁 Go forces you to handle errors at every call site. TypeScript doesn't — any function can throw and the compiler won't warn you. How do you get Go-style error discipline in a language that doesn't require it?

TypeScript gives you try/catch with an unknown catch variable and zero compiler enforcement. No checked exceptions. No val, err tuples. Just unknown and good habits.

Here's how to make it work.

The Catch Block Problem

The catch variable is unknown, not Error.

try {
  JSON.parse("not json");
} catch (err) {
  // err is `unknown`, not `Error`
  console.log(err.message);
  // TS error: 'err' is of type 'unknown'
}

Why? Because anything can be thrown. A string, a number, null, an object. TypeScript can't assume it's an Error.

Always Narrow

try {
  JSON.parse("not json");
} catch (err) {
  if (err instanceof Error) {
    console.log(err.message); // Unexpected token 'n'
  } else {
    console.log("Unknown error:", err);
  }
}

Check instanceof Error first, then handle the rest. Every time.

Never Throw Strings

Legal. Terrible practice.

// Don't do this
throw "something went wrong";
throw 404;
throw { code: "NOT_FOUND" };

Always throw Error instances. They carry a stack trace. Strings don't.

// Do this
throw new Error("something went wrong");

If you throw strings, your instanceof Error checks in catch blocks miss them. Silent failures.

Custom Error Classes

Extend Error to create custom error classes — typed, distinguishable errors.

export class NotFoundError extends Error {
  constructor(resource: string, id: string) {
    super(`${resource} with id ${id} not found`);
    this.name = "NotFoundError";
  }
}

export class ValidationError extends Error {
  constructor(
    public readonly field: string,
    message: string
  ) {
    super(message);
    this.name = "ValidationError";
  }
}
import { NotFoundError, ValidationError } from "./errors.js";

function getUser(id: string) {
  throw new NotFoundError("User", id);
}

try {
  getUser("abc-123");
} catch (err) {
  if (err instanceof NotFoundError) {
    console.log(err.message); // User with id abc-123 not found
    console.log(err.name);    // NotFoundError
  } else if (err instanceof ValidationError) {
    console.log(err.field);
  }
}

Set this.name. It shows up in stack traces and logs. Without it, every custom error just says "Error".

The Cause Chain

ES2022 added error cause to Error. Wrap errors with context without losing the original.

async function fetchUser(id: string): Promise<object> {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } catch (err) {
    throw new Error(`Failed to fetch user ${id}`, { cause: err });
  }
}
try {
  await fetchUser("123");
} catch (err) {
  if (err instanceof Error) {
    console.log(err.message);        // Failed to fetch user 123
    console.log(err.cause);          // Error: HTTP 404
  }
}

Chain causes as deep as you want. Each layer adds context. Walk the chain to find the root cause:

function getRootCause(err: Error): Error {
  let current = err;
  while (current.cause instanceof Error) {
    current = current.cause;
  }
  return current;
}

Async Error Handling

With async/await, try/catch works the same as synchronous code.

import { readFile } from "node:fs/promises";

async function loadConfig(): Promise<string> {
  try {
    const data = await readFile("config.json", "utf-8");
    return data;
  } catch (err) {
    if (err instanceof Error) {
      throw new Error("Config load failed", { cause: err });
    }
    throw err;
  }
}

You can also use .catch() on promises. Fine for one-liners.

// .catch() style - fine for one-liners
const data = await readFile("config.json", "utf-8")
  .catch(() => "{}"); // default to empty JSON on failure

console.log(data); // {} (if file doesn't exist)

Unhandled Promise Rejections

Forget to catch an async error and Node.js crashes your process (Node 15+). Good. It forces you to handle errors.

// This will crash if fetchUser throws
async function main() {
  const user = await fetchUser("123"); // unhandled rejection if this throws
}

main(); // No .catch(), no try/catch = crash

Always handle errors at the top level.

A Wrapper for Cleaner Handling

Want val, err tuples? Build them.

async function tryCatch<T>(
  fn: () => Promise<T>
): Promise<[T, null] | [null, Error]> {
  try {
    const result = await fn();
    return [result, null];
  } catch (err) {
    if (err instanceof Error) return [null, err];
    return [null, new Error(String(err))];
  }
}
const [user, err] = await tryCatch(() => fetchUser("123"));

if (err) {
  console.log("Failed:", err.message);
  // handle error, return early
} else {
  console.log("Got user:", user);
}

The tuple return forces you to check the error before using the value. No exceptions involved.

The Result Type Pattern

A discriminated union for explicit error handling. Same idea as Rust's Result<T, E>.

type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

function ok<T>(value: T): Result<T, never> {
  return { ok: true, value };
}

function fail<E>(error: E): Result<never, E> {
  return { ok: false, error };
}
function parsePort(input: string): Result<number, string> {
  const port = parseInt(input, 10);
  if (isNaN(port)) return fail(`Invalid port: ${input}`);
  if (port < 1 || port > 65535) return fail(`Port out of range: ${port}`);
  return ok(port);
}

const result = parsePort("8080");

if (result.ok) {
  console.log(result.value); // 8080 (type: number)
} else {
  console.log(result.error); // (type: string)
}

The compiler narrows the type after the if check. Inside the ok: true branch, result.value exists and is typed. Inside ok: false, result.error exists and is typed. No casting.

When to Use Result vs Throw

throw for truly exceptional situations: network failures, corrupted data, bugs. Result for expected failures: validation errors, parsing failures, business rule violations.

// Expected failure: use Result
function validateEmail(input: string): Result<string, string> {
  if (!input.includes("@")) return fail("Missing @");
  return ok(input);
}

// Exceptional failure: throw
async function connectDB(url: string): Promise<Connection> {
  const conn = await pool.connect(url);
  if (!conn) throw new Error("Database connection failed");
  return conn;
}

Key Takeaways

  • The catch variable is unknown. Always narrow with instanceof Error before accessing .message or .stack.
  • Never throw strings or plain objects. Always throw Error instances so you get stack traces.
  • Use custom error classes with this.name set for distinguishable, catchable error types.
  • Use { cause: err } to chain errors with context, just like Go's %w wrapping.
  • The tryCatch wrapper gives you Go-style [value, error] tuple returns if you prefer that pattern.
  • The Result<T, E> discriminated union gives you Rust-style compile-time error checking with no exceptions.
  • Use throw for exceptional failures. Use Result for expected, recoverable failures.

🎁 Go has go build — one command, sensible defaults, no config file. TypeScript has tsconfig.json, a dozen options that interact with each other, and tools that need extra wiring to agree. What's the minimal setup that actually works for a Node.js backend?

📝 Ready to test your knowledge?

Answer the quiz below to mark this lesson complete.

Spot something off? Report an issue