Skip to content

uncaught-propagation ​

A PropagateError reaches a place where nothing can catch it.

Why: a PropagateError must be caught somewhere up the call chain. Two places have nothing above them: code running at module top level, and callbacks invoked later by someone else (timers, event handlers, forEach(async ...)). Guides: Errors, Async.

ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class MissingEnv extends PropagateError {}

function requireEnv(name: string): string {
  const value = process.env[name];
  if (value === undefined) throw new MissingEnv(name);
  return value;
}

export const databaseUrl = requireEnv("DATABASE_URL");
✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class MissingEnv extends PropagateError {}

function requireEnv(name: string): string {
  const value = process.env[name];
  if (value === undefined) throw new MissingEnv(name);
  return value;
}

function start(): void {
  const databaseUrl = requireEnv("DATABASE_URL");
  console.log(`connecting to ${databaseUrl}`);
}

try {
  start();
} catch (error) {
  console.error(error);
  process.exitCode = 1;
}

A callback runs after the code that registered it has finished, so a try around the registration doesn't help:

ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class Invalid extends PropagateError {}

function check(value: string): void {
  if (value === "") throw new Invalid("empty");
}

type Input = { readonly addEventListener: (type: string, listener: () => void, options: { signal: AbortSignal }) => void };

export function watch(input: Input, signal: AbortSignal): void {
  try {
    input.addEventListener("change", () => {
      check("");
    }, { signal });
  } catch {
    console.error("never runs for errors inside the listener");
  }
}

Catch inside the callback instead.

A callback handed to one of your own functions is followed into it. If that function calls the parameter right away (not in a timer, not after an await), the callback runs inside the call, so a try around the call catches it, and so does a catch in the function itself. "Right away" also covers a const copy of the parameter (const pick = choose ?? fallback, choose || fallback, custom ? choose : fallback), handing it on to another function that calls it right away (function run(fn) { return guarded(fn); }, up to three functions deep), and an async function calling it before its first await: there, what the callback throws rejects the function's promise, so awaiting that promise inside a try catches it (a promise nobody awaits counts as detached). Array.from(list, mapper) and the typed arrays' from (Int32Array.from(list, mapper)) call the mapper right away, like map. A helper that turns a PropagateError into a Result at a boundary works:

✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, PropagateError, type Result } from "@evobug_com/safe-ts-std/result";

class ProtocolFailure extends PropagateError {}

export type HeaderError = Enum<{ Malformed: { reason: string } }>;
export const HeaderError = constructors<HeaderError>();

function readByte(bytes: number[], at: number): number {
  const byte = bytes[at];
  if (byte === undefined) throw new ProtocolFailure(`no byte at ${at}`);
  return byte;
}

function catchProtocol<T>(op: () => T): Result<T, HeaderError> {
  try {
    return op();
  } catch (e) {
    if (e instanceof ProtocolFailure) return err(HeaderError.Malformed({ reason: e.message }));
    throw e;
  }
}

export function header(bytes: number[]): Result<number, HeaderError> {
  return catchProtocol(() => readByte(bytes, 0) * 256 + readByte(bytes, 1));
}
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, PropagateError, type Result } from "@evobug_com/safe-ts-std/result";

class ProtocolFailure extends PropagateError {}

export type HeaderError = Enum<{ Malformed: { reason: string } }>;
export const HeaderError = constructors<HeaderError>();

function readByte(bytes: number[], at: number): number {
  const byte = bytes[at];
  if (byte === undefined) throw new ProtocolFailure(`no byte at ${at}`);
  return byte;
}

function catchProtocol<T>(op: () => T): Result<T, HeaderError> {
  try {
    return op();
  } catch (e) {
    if (e instanceof ProtocolFailure) return err(({ tag: "Malformed", reason: e.message } satisfies HeaderError as HeaderError));
    throw e;
  }
}

export function header(bytes: number[]): Result<number, HeaderError> {
  return catchProtocol(() => readByte(bytes, 0) * 256 + readByte(bytes, 1));
}

An async callback written in the call (step("save", async () => { await save(); })) is followed the same way as one in a const: what it rejects with goes where the function sends the promise it gets from calling it, wherever that call is. try { await work(); } catch {...} in the function catches it, await work() with no try makes it the function's own rejection (so a try around await step(...) catches it), and a call whose promise is dropped (void work(), a timer) leaves it detached:

✅ Accepted: step awaits the callback inside its try

✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class Offline extends PropagateError {}

async function upload(name: string): Promise<void> {
  if (name === "") throw new Offline("no connection");
}

async function step(name: string, work: () => Promise<void>): Promise<void> {
  try {
    await work();
  } catch (error) {
    console.error(`${name} failed`, error);
  }
}

export async function publish(): Promise<void> {
  await step("upload", async () => {
    await upload("report.pdf");
  });
}

A function that keeps the callback and calls it later is treated like a timer: what the callback throws is reported inside it. Where the parameter's type is a function type written in the project, the callback is checked against that type instead, by failure-contract: a type that declares the failure (Throwing<[id: string], string, NotFound>) lets it through, and the call that runs it later propagates what the type declares.

✅ Accepted: the default renderer is a const copy, and withSession hands the callback on to the function with the try. Both trys are the top of a request, which answers 401.

✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class Unauthorized extends PropagateError {}

type Reply = { readonly status: number; readonly body: string };

const signIn: Reply = { status: 401, body: "sign in" };

function userOf(token: string): string {
  if (token === "") throw new Unauthorized("no session");
  return token;
}

function page(tokens: string[], render?: (tokens: string[]) => string): string {
  const show = render ?? ((list: string[]) => `${list.length} sessions`);
  return show(tokens);
}

export function sessions(tokens: string[]): Reply {
  try {
    return { status: 200, body: page(tokens, (list) => userOf(list[0] ?? "")) };
  } catch (e) {
    if (e instanceof Unauthorized) return signIn;
    throw e;
  }
}

function respond(work: () => string): Reply {
  try {
    return { status: 200, body: work() };
  } catch (e) {
    if (e instanceof Unauthorized) return signIn;
    throw e;
  }
}

function withSession(work: () => string): Reply {
  return respond(work);
}

export function profile(token: string): Reply {
  return withSession(() => `<h1>${userOf(token)}</h1>`);
}

A generator's body runs where it is stepped, not where it is made: for (const row of rows), rows.next(), [...rows], yield* rows and Array.from(rows). When the generator is kept in a const (or a let only ever set to the call) and every use of it steps it, its throws count there, so a generator made before a try and stepped inside it is caught, and one made inside a try and stepped after it is not. Otherwise (returned, passed on, stored), they count where it is made.

When a reported path is long and leaves the file (selectItem → addToCart → checkoutStep → ... → throw), the help names the first function on it in another file: a boundary there (a try around that call, or a Result from it) covers every path through it.

Vue calls a component's functions the same way: <script setup>, and, in defineComponent(...), createApp(...) or a .vue file's export default { ... }, the setup option (a method, a function or an arrow), the render function it returns, render, data, the lifecycle hooks, computed getters and setters and watch handlers. The function form, defineComponent((props) => ...), too. methods are followed like any function. The options must be written in the call or in export default. See Vue: errors.

Some functions outside the project are known to catch what the functions handed to them throw:

  • Test runners. The runner calls a test, a suite or a hook and reports what it throws or rejects with as a failed test: test, it, describe, suite, before, after, beforeEach, afterEach, beforeAll and afterAll, also with .skip, .only, .concurrent, .each(table)(...), .skipIf(condition)(...) and the like, and node:test subtests (t.test(...)). They are recognized when imported from node:test or vitest, from a package that re-exports one of them (export * from "vitest", as vite-plus/test does, or export { test } from "vitest", also through a few such modules), from a module listed in "safe-ts": { "testRunners": ["@acme/test-kit"] } in package.json (for re-exports the checker can't read, such as a CommonJS module.exports = require("vitest")), or used as globals (Vitest's globals: true) when nothing in the file declares the name.
  • Assertions that expect a throw. node:assert's assert.throws(fn), assert.doesNotThrow(fn), assert.rejects(fn) and assert.doesNotReject(fn); Chai's assert.throws(fn), assert.doesNotThrow(fn) and expect(fn).to.throw() (from chai, or Vitest's assert and expect, which are Chai's); Vitest's expect(fn).toThrow(), toThrowError(...), .not.toThrow() and await expect(promise).rejects.toThrow(). They call fn and catch what it throws (or the promise rejects with).
  • Mock implementations. vi.fn(impl), spy.mockImplementation(impl) and mockImplementationOnce(impl), and node:test's mock.fn(impl) and mock.method(object, name, impl) (also as t.mock....). impl stands in for the mocked function, so what it throws is the failure the test fakes: the code under test calls it, and the test runner is above that. Written inline or first in a const, it is treated the same.
  • std. check(arb, property) runs the property right away and counts a throw as a failed run. withTimeout(work, ms) turns what work throws or rejects with into its Failed outcome, and mapLimit(items, n, fn) into an Err. settleAll(promises) and firstOk(promises) turn rejections into Errs, like Promise.allSettled, also for the promises a .map(...) callback returns (settleAll(urls.map((url) => load(url)))).

✅ Accepted: the test runner catches what the test throws, and the mock fakes a failure

✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { mock, test } from "node:test";

import { PropagateError } from "@evobug_com/safe-ts-std/result";

class Offline extends PropagateError {}

type Reply = { readonly status: number; readonly body: string };

const api = {
  fetchName(id: string): string {
    if (id === "") throw new Offline("no id");
    return `user ${id}`;
  },
};

/** The top of the greeting request: offline answers 503. */
function greet(id: string): Reply {
  try {
    return { status: 200, body: `Hello, ${api.fetchName(id)}` };
  } catch (error) {
    if (error instanceof Offline) return { status: 503, body: "try again later" };
    throw error;
  }
}

test("names the user", () => {
  assert.equal(api.fetchName("1"), "user 1");
});

test("answers 503 when offline", () => {
  mock.method(api, "fetchName", () => {
    throw new Offline("no network");
  });
  assert.equal(greet("1").status, 503);
});

A timer or a listener started inside a test still runs after the test is over, so what its callback throws is reported as usual.

A call that passes a literal for a flag the function tests is judged with that value. Code under if (strict), strict && ..., strict ? ... : ..., or after if (!strict) return, doesn't count for packetBytes(packet, false); it does for packetBytes(packet, true) and packetBytes(packet, strict). Only the function called directly is narrowed this way, and only for a parameter it never assigns.

A catch that rethrows some kinds doesn't catch those:

ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class MissingEnv extends PropagateError {}
class EmptyEnv extends PropagateError {}

function requireEnv(name: string): string {
  const value = process.env[name];
  if (value === undefined) throw new MissingEnv(name);
  if (value === "") throw new EmptyEnv(name);
  return value;
}

try {
  console.log(requireEnv("DATABASE_URL"));
} catch (error) {
  if (error instanceof MissingEnv) console.error("set DATABASE_URL");
  else throw error;
}

A named function handed to the runtime as an entry point is in the same place as a callback: a timer (setTimeout, setInterval, setImmediate, queueMicrotask, process.nextTick, requestAnimationFrame), a listener (target.on(type, fn), once, addEventListener), a request handler (http.createServer(fn)), or an event handler property (worker.onmessage = fn, socket.onclose = () => ...; on an object of a type the project declares, port.onmessage = fn is a member like any other, checked against its type by failure-contract). The runtime calls it, so a PropagateError from it crashes a Node process (or is only logged in a browser), and an async one is an unhandled rejection:

ts
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";

import { PropagateError } from "@evobug_com/safe-ts-std/result";

class NotFound extends PropagateError {}

function page(url: string): string {
  if (url !== "/") throw new NotFound(url);
  return "<h1>Home</h1>";
}

function handle(req: IncomingMessage, res: ServerResponse): void {
  res.end(page(req.url ?? "/"));
}

export function serve(port: number): void {
  createServer(handle).listen(port);
}

✅ Accepted: the handler is the top level, so it catches

✓ Accepted0 diagnostics
ts
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";

import { PropagateError } from "@evobug_com/safe-ts-std/result";

class NotFound extends PropagateError {}

function page(url: string): string {
  if (url !== "/") throw new NotFound(url);
  return "<h1>Home</h1>";
}

function handle(req: IncomingMessage, res: ServerResponse): void {
  try {
    res.end(page(req.url ?? "/"));
  } catch (error) {
    res.writeHead(error instanceof NotFound ? 404 : 500).end();
  }
}

export function serve(port: number): void {
  createServer(handle).listen(port);
}

A function passed by name anywhere else is the arrow that calls it, written where the name is: apply(find) gets what apply((id) => find(id)) gets (followed into apply), list.map(find) what list.map((id) => find(id)) gets (it runs right away), and .then(find), a library's callback or a function of yours that keeps it for later what a callback run later gets. find.call(...), find.bind(...)(...) and Reflect.apply(find, ...) are calls of find, and a copy is the function it copies: const load = find, const { find: load } = api, a class field handler = find, also exported and called from another file.

A call that only looks a function used by name up, compares it, takes it out or prints it never calls it: handlers.includes(find), seen.has(find), seen.delete(onChange), handlers.indexOf(find), el.removeEventListener("change", onChange), emitter.off("change", onChange), Object.is(find, onChange), String(find), console.log(find). The method's name counts when the receiver is positively a built-in (an array, a Set or Map, console, Object, a DOM target, by how it is declared or made). On any other receiver it counts only where it can't mean anything else: taking a listener out (removeEventListener, off, removeListener), and includes, indexOf, lastIndexOf, has and delete with the function as the only argument; app.delete("/item", remove) is a route and logger.debug(describe) a lazy message, both called later. A function of yours is judged by what it does with the parameter (function known(f) { return registry.includes(f); } never calls it). A function written in place is always meant to be called, whatever the method is named. Kept in a collection (handlers.push(find), seen.add(find), table.set(key, find), a function of yours that stores it), it is called later by whoever reads the collection, with nothing of the code that kept it above, so it is reported as a callback run later is, in both forms. Where the collection is declared with a function type (handlers: Set<(id: string) => string>), what goes in is held to that type instead (failure-contract):

❌ Rejected: (id: string) => string declares no failure

✕ Rejectedfailure-contract
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class Missing extends PropagateError {}

function find(id: string): string {
  if (id === "") throw new Missing("no id");
  return id;
}

export function register(handlers: Mut<Set<(id: string) => string>>): void {
  handlers.add(find);
}

✅ Accepted: a lookup and a removal by name

✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class Missing extends PropagateError {}

function find(id: string): string {
  if (id === "") throw new Missing("no id");
  return id;
}

export function unregister(handlers: Mut<Set<(id: string) => string>>): boolean {
  return handlers.has(find) && handlers.delete(find);
}

❌ Rejected: the .then callback runs after renew has returned

ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class Expired extends PropagateError {}

function refresh(token: string): string {
  if (token === "") throw new Expired("session expired");
  return token;
}

export function renew(tokens: Promise<string>): void {
  void tokens.then(refresh);
}

✅ Accepted: awaited in the function that catches it

✓ Accepted0 diagnostics
ts
import { type Option, PropagateError } from "@evobug_com/safe-ts-std/result";

class Expired extends PropagateError {}

function refresh(token: string): string {
  if (token === "") throw new Expired("session expired");
  return token;
}

export async function renew(tokens: Promise<string>): Promise<Option<string>> {
  try {
    return refresh(await tokens);
  } catch (error) {
    if (error instanceof Expired) return undefined;
    throw error;
  }
}

Quick fix: Wrap in try/catch (when the call is a statement in a callback or at top level; not for a function passed by name: catch inside that function).

What the rule can't see: calls it can't tie to one function or to a declared type: a method on a value whose class the source doesn't write down one hop away (typed with a union, or with a type parameter of the function it is in). A value typed with any written form of a class's type counts as written down: a generic alias or interface given the class (Services<Repo>), Readonly / Partial / Pick / Omit / Required / NonNullable / Awaited / std's Option / Mut of one, a union with undefined or null, a Map's get, an array's or tuple's item (also destructured), a Record's value, what iterating a Map or Set gives (also values(), entries(), keys()), await of a Promise<Repo> and its .then callback's parameter; an optional call (repo?.load()) is followed like the plain one. A call through an interface, an object type, an abstract method, a base class or a callback's type propagates what that type declares with Throws<R, E> or Throwing<Args, R, E> (nothing when it declares nothing), however the callback is reached: a Record's or index signature's value by name or by a key (jobs[name]?.(), also taken out into a checked local), a Map's value (byName.get(name)?.()), an array's or tuple's item (jobs[0]?.()), a computed key of an object type whose members agree; what is put there is checked against it by failure-contract, so an override, an implementation or a stored callback can't fail with more. A receiver is tied to its class through a field declared with it (this.repo.load() with private readonly repo: Repo, = new Repo(), a constructor parameter property, or this.repo = new Repo() in the constructor), a property of a declared type (deps.repo.load() with deps: Deps), a function declared to return it (makeRepo().load(), (await openRepo()).load()), and a member chain into a module-level object or one a readonly field holds (api.users.load(), this.api.load()), across files; reading x.value runs its getter (also destructured, const { value } = x) and x.value = v its setter; a tagged template calls its tag and a decorator its function. A method the language calls for you (toString, toJSON, [Symbol.iterator], then, ...) isn't followed where it runs: implicit-propagation refuses one that can propagate, where it is defined. A function passed by name is followed where the arrow standing for it would be, and not where that arrow isn't: stored in an object or array literal written inside a function and called through it (const h = { load: find }; h.load(id)), picked in an argument (apply(strict ? find : lookup), apply(...handlers)), a default parameter value (function run(load = find)), a JSX prop that isn't an event handler (render={find}). Errors propagating through those are not reported, rather than guessed at. The checker has no type information beyond what is written at the call: a call on a mapped type over a class reports no caller. A function stored in an object or a field ({ read: () => ... }) isn't followed as a body: a call through the object's declared type propagates what that type declares, and the function is checked against it (failure-contract); with no declared type, what it throws is neither reported where it is written nor counted against the function that made the object. A callback written as an argument is followed only into a function the analysis can find (the same ones calls are followed into); an async callback counts as detached, and so does a call an async function makes after its first await. In a catch, only instanceof tests (with !, &&, ||) are understood; after any other test, throw e counts as rethrowing every kind. A branch ends at return, throw, and calls that never return: assert.fail(...) (and fail imported from node:assert), process.exit(...), std's unreachable(...), and the file's own functions declared : never. assert.throws(fn) and assert.rejects(fn) from node:assert (and the other assertions listed above) call fn and catch what it throws or rejects with, like unsafe and unsafeAsync. A function handed to the runtime is only recognized for the entry points listed above, and only when it is named the way calls are followed (declared here or imported, a nested helper, or a member such as store.handle); app.get("/", handle) and other framework routes are not judged, since frameworks usually catch what their handlers throw. A listener on your own EventEmitter is treated like any other listener, although emit() calls it right away.

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra