Errors
In plain TypeScript, any function can throw without saying so in its type—leaving callers to discover failures in production. SAFE-TS makes every failure explicit so errors are handled at the boundary where they happen.
In short
- Recoverable failures (bad input, missing record): return
Result<T, E>with a named error enum. - Abort the whole request or job: throw a
PropagateErrorsubclass and catch it once at the top boundary. - Calling throwing APIs (
JSON.parse,new URL, libraries): wrap inunsafe(...)ortry, or use the feature pack's safe wrapper. - No plain
throw new Error(...): untracked exceptions are hidden from callers and rejected byno-throw.
When a function can fail, return the error
❌ Rejected: callers can't see that this throws
✕ Rejectedno-throw
ts
export function parseAge(input: string): number {
const age = Number(input);
if (!Number.isInteger(age) || age < 0) throw new Error(`not an age: ${input}`);
return age;
}Result<number, AgeError> means "a number, or an AgeError". The error type is an enum that lists the ways it can fail, so a caller can handle each one. Return the number as usual, or err(...) when it fails. The caller can't use the result as a number until it has checked with isErr; TypeScript makes sure of that.
✓ Accepted0 diagnostics
ts
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
export type AgeError = Enum<{ NotANumber: { input: string }; Negative: {} }>;
export const AgeError = constructors<AgeError>();
export function parseAge(input: string): Result<number, AgeError> {
const age = Number(input);
if (!Number.isInteger(age)) return err(AgeError.NotANumber({ input }));
if (age < 0) return err(AgeError.Negative());
return age;
}
export function describe(input: string): string {
const age = parseAge(input);
if (isErr(age)) {
return match(age.error, {
NotANumber: ({ input }) => `not an age: ${input}`,
Negative: () => "an age can't be negative",
});
}
return age >= 18 ? "adult" : "minor";
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
export type AgeError = Enum<{ NotANumber: { input: string }; Negative: {} }>;
export const AgeError = constructors<AgeError>();
export function parseAge(input: string): Result<number, AgeError> {
const age = Number(input);
if (!Number.isInteger(age)) return err(({ tag: "NotANumber", input } satisfies AgeError as AgeError));
if (age < 0) return err(({ tag: "Negative" } satisfies AgeError as AgeError));
return age;
}
export function describe(input: string): string {
const age = parseAge(input);
if (isErr(age)) {
{ const __ms1 = age.error; let __mv1: string; switch (__ms1.tag) {
case "NotANumber": { const { input } = __ms1; __mv1 = `not an age: ${input}`; break; }
case "Negative": { __mv1 = "an age can't be negative"; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}
return age >= 18 ? "adult" : "minor";
}The words the user sees come from one match over the error, at the edge where they are shown. More on this in Give errors names.
The same goes for a message used as an error: a function that returns '' when it worked and a message when it didn't leaves the test to the caller (if (error) ...), and nothing makes the caller write it. Return a Result<void, E> with a named E instead. With the idiomatic rules on, sentinel-error finds those functions.
If every failure just means "use a default", unwrapOr says that in one call:
✓ Accepted0 diagnostics
ts
import { parseInteger } from "@evobug_com/safe-ts-std/number";
import { unwrapOr } from "@evobug_com/safe-ts-std/result";
export function portOrDefault(text: string): number {
return unwrapOr(parseInteger(text), 8080);
}Pass an error up with q(...)
Checking after every call gets repetitive. q(...) gives you the value, or, if it's an error, returns that error from your function right there. (It's Rust's ?, if you know it.) The build turns it into the if you would have written, so it costs nothing.
✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, q, type Result } from "@evobug_com/safe-ts-std/result";
type Span = { readonly from: number; readonly to: number };
export type SpanError = Enum<{ NotANumber: { text: string }; Reversed: {} }>;
export const SpanError = constructors<SpanError>();
function parseNumber(text: string): Result<number, SpanError> {
const value = Number(text);
return Number.isFinite(value) ? value : err(SpanError.NotANumber({ text }));
}
export function parseSpan(text: string): Result<Span, SpanError> {
const [fromText = "", toText = ""] = text.split("-");
const from = q(parseNumber(fromText));
const to = q(parseNumber(toText));
if (from > to) return err(SpanError.Reversed());
return { from, to };
}ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { err, q, type Result } from "@evobug_com/safe-ts-std/result";
type Span = { readonly from: number; readonly to: number };
export type SpanError = Enum<{ NotANumber: { text: string }; Reversed: {} }>;
export const SpanError = constructors<SpanError>();
function parseNumber(text: string): Result<number, SpanError> {
const value = Number(text);
return Number.isFinite(value) ? value : err(({ tag: "NotANumber", text } satisfies SpanError as SpanError));
}
export function parseSpan(text: string): Result<Span, SpanError> {
const [fromText = "", toText = ""] = text.split("-");
const __q1 = parseNumber(fromText); if (__q1 instanceof __qErr) return __q1; const from = __q1;
const __q2 = parseNumber(toText); if (__q2 instanceof __qErr) return __q2; const to = __q2;
if (from > to) return err(({ tag: "Reversed" } satisfies SpanError as SpanError));
return { from, to };
}Two limits: the function has to return a Result, and q(...) has to be a statement of its own (const x = q(...), x = q(...), q(...); or return q(...)).
The hand-written if (isErr(x)) return x; passes the default rules too. Write q(...): with the idiomatic rules on, prefer-q reports it (with a quick fix), and prefer-map-err an isErr branch that re-wraps the error (return err(f(x.error))).
❌ Rejected: q(...) in the middle of an expression
✕ Rejectedq-position
ts
import { q, type Result } from "@evobug_com/safe-ts-std/result";
declare function parseNumber(text: string): Result<number, string>;
export function double(text: string): Result<number, string> {
return 2 * q(parseNumber(text));
}Fix: const n = q(parseNumber(text)); return 2 * n;
When the error type is a different one
q(result, mapError) returns mapError(error) instead of the error itself, so a function can pass up an error of its own type in one line (Rust's ? does this with From). mapError runs only when there is an error. Without one, the error passes up as it is, and it must be one the function declares: q gives TypeScript the value, so only q-undeclared-error sees an error the function's type doesn't list. Outside q, mapErr(result, mapError) maps a Result's error and keeps its value.
✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, q, type Result } from "@evobug_com/safe-ts-std/result";
type Upload = { readonly size: number };
export type CheckError = Enum<{ Empty: {}; TooLarge: { limit: number } }>;
export const CheckError = constructors<CheckError>();
export type UploadError = Enum<{ Invalid: { reason: CheckError }; Offline: {} }>;
export const UploadError = constructors<UploadError>();
function checkUpload(size: number): Result<Upload, CheckError> {
if (size === 0) return err(CheckError.Empty());
if (size > 1_000_000) return err(CheckError.TooLarge({ limit: 1_000_000 }));
return { size };
}
export function startUpload(size: number): Result<Upload, UploadError> {
const upload = q(checkUpload(size), (reason) => UploadError.Invalid({ reason }));
return upload;
}ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { Err as __qErr, mapErr as __qMapErr } from "@evobug_com/safe-ts-std/result"; import { err, q, type Result } from "@evobug_com/safe-ts-std/result";
type Upload = { readonly size: number };
export type CheckError = Enum<{ Empty: {}; TooLarge: { limit: number } }>;
export const CheckError = constructors<CheckError>();
export type UploadError = Enum<{ Invalid: { reason: CheckError }; Offline: {} }>;
export const UploadError = constructors<UploadError>();
function checkUpload(size: number): Result<Upload, CheckError> {
if (size === 0) return err(({ tag: "Empty" } satisfies CheckError as CheckError));
if (size > 1_000_000) return err(({ tag: "TooLarge", limit: 1_000_000 } satisfies CheckError as CheckError));
return { size };
}
export function startUpload(size: number): Result<Upload, UploadError> {
const __q1 = checkUpload(size); if (__q1 instanceof __qErr) return __qMapErr(__q1, (reason) => ({ tag: "Invalid", reason } satisfies UploadError as UploadError)); const upload = __q1;
return upload;
}Don't drop a Result
Calling a function and ignoring its Result throws the error away without anyone noticing. So does keeping it in a local that nothing looks at on the way to the end of the function (const r = save(name); console.log(r);): logging it isn't handling it (must-use-result).
✕ Rejectedmust-use-result
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";
export type SaveError = Enum<{ EmptyName: {}; Taken: { name: string } }>;
export const SaveError = constructors<SaveError>();
function save(name: string): Result<void, SaveError> {
return name === "" ? err(SaveError.EmptyName()) : undefined;
}
export function rename(name: string): void {
save(name);
}ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";
export type SaveError = Enum<{ EmptyName: {}; Taken: { name: string } }>;
export const SaveError = constructors<SaveError>();
function save(name: string): Result<void, SaveError> {
return name === "" ? err(({ tag: "EmptyName" } satisfies SaveError as SaveError)) : undefined;
}
export function rename(name: string): void {
save(name);
}Pass it up with q(...), handle it where the user sees the outcome, or write void to say you don't care:
✓ Accepted0 diagnostics
ts
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, q, type Result } from "@evobug_com/safe-ts-std/result";
export type SaveError = Enum<{ EmptyName: {}; Taken: { name: string } }>;
export const SaveError = constructors<SaveError>();
function save(name: string): Result<void, SaveError> {
return name === "" ? err(SaveError.EmptyName()) : undefined;
}
export function rename(name: string): Result<void, SaveError> {
q(save(name));
return undefined;
}
export function renameMessage(name: string): string {
const saved = save(name);
if (!isErr(saved)) return "saved";
return match(saved.error, {
EmptyName: () => "a name can't be empty",
Taken: ({ name }) => `${name} is taken`,
});
}
export function renameBestEffort(name: string): void {
void save(name);
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { err, isErr, q, type Result } from "@evobug_com/safe-ts-std/result";
export type SaveError = Enum<{ EmptyName: {}; Taken: { name: string } }>;
export const SaveError = constructors<SaveError>();
function save(name: string): Result<void, SaveError> {
return name === "" ? err(({ tag: "EmptyName" } satisfies SaveError as SaveError)) : undefined;
}
export function rename(name: string): Result<void, SaveError> {
{ const __q1 = save(name); if (__q1 instanceof __qErr) return __q1; __q1; }
return undefined;
}
export function renameMessage(name: string): string {
const saved = save(name);
if (!isErr(saved)) return "saved";
{ const __ms1 = saved.error; let __mv1: string; switch (__ms1.tag) {
case "EmptyName": { __mv1 = "a name can't be empty"; break; }
case "Taken": { const { name } = __ms1; __mv1 = `${name} is taken`; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}
export function renameBestEffort(name: string): void {
void save(name);
}A generic function that returns a Result
Result<T, E> is T | Err<E>, so with T = unknown it is just unknown: the Err<E> is gone from the type. That happens without anyone writing unknown, at a call of a generic function that leaves T open. An endpoint declared <T>(path) => Promise<Result<T, RequestError>> and called as send(path), with no type argument and no type around the call to infer it from, gets T = unknown: isErr(answer) then hands back an Err<unknown>, which a function returning Result<void, RequestError> can't return. The checker reports the declaration (no-unknown-in-result):
✕ Rejectedno-unknown-in-result
ts
import type { Result } from "@evobug_com/safe-ts-std/result";
type RequestError = { readonly status: number };
export declare function send<T>(path: string): Promise<Result<T, RequestError>>;Give T a default. A call that doesn't say gets it, and the error type stays:
✓ Accepted0 diagnostics
ts
import { q, type Result } from "@evobug_com/safe-ts-std/result";
type RequestError = { readonly status: number };
export declare function send<T = undefined>(path: string): Promise<Result<T, RequestError>>;
export async function ping(): Promise<Result<void, RequestError>> {
q(await send("/ping")); // a Result<undefined, RequestError>: its error passes up
return undefined;
}ts
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q, type Result } from "@evobug_com/safe-ts-std/result";
type RequestError = { readonly status: number };
export declare function send<T = undefined>(path: string): Promise<Result<T, RequestError>>;
export async function ping(): Promise<Result<void, RequestError>> {
{ const __q1 = await send("/ping"); if (__q1 instanceof __qErr) return __q1; __q1; } // a Result<undefined, RequestError>: its error passes up
return undefined;
}undefined makes a forgotten type argument show: reading the answer as anything else is a type error. A call that reads the answer says what it is (send<User>(path)), or the function takes it from an argument, a validator (load(path, (value) => validate<User>(value))), and then no default is needed.
Give errors names
Every example on this page names its errors: the error type is an enum of the failures a caller handles differently. A caller then reacts to each one with match, and when a new failure is added, every match that misses it stops compiling. The words a user reads are written once, in that match, where they are shown. When several places show the same words, that match becomes a method of the enum, error.describe() (Methods on an enum), not a copy in each place.
A plain string error (Result<T, string>) passes the checker, but a message can't be handled by kind: a caller that needs to tell "wrong password" from "locked" has to compare the text. Name the failures from the start:
✓ Accepted0 diagnostics
ts
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
export type LoginError = Enum<{
UnknownUser: { name: string };
WrongPassword: {};
Locked: { until: string };
}>;
declare function login(name: string, password: string): Result<string, LoginError>;
export function loginMessage(name: string, password: string): string {
const session = login(name, password);
if (!isErr(session)) return "welcome";
return match(session.error, {
UnknownUser: ({ name }) => `no user called ${name}`,
WrongPassword: () => "wrong password",
Locked: ({ until }) => `locked until ${until}`,
});
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
export type LoginError = Enum<{
UnknownUser: { name: string };
WrongPassword: {};
Locked: { until: string };
}>;
declare function login(name: string, password: string): Result<string, LoginError>;
export function loginMessage(name: string, password: string): string {
const session = login(name, password);
if (!isErr(session)) return "welcome";
{ const __ms1 = session.error; let __mv1: string; switch (__ms1.tag) {
case "UnknownUser": { const { name } = __ms1; __mv1 = `no user called ${name}`; break; }
case "WrongPassword": { __mv1 = "wrong password"; break; }
case "Locked": { const { until } = __ms1; __mv1 = `locked until ${until}`; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}When the whole request should stop: PropagateError
Sometimes a failure deep down should end everything up to one place: a request handler, a job, a CLI command. Passing a Result through ten functions that can't do anything about it is just noise. Throw a subclass of PropagateError instead. SAFE-TS tracks which functions can throw it, and requires a try/catch somewhere above them.
✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
export class NotFound extends PropagateError {}
export class Forbidden extends PropagateError {}
function findDocument(id: string): string {
if (id === "") throw new NotFound("no id");
return `document ${id}`;
}
function readDocument(user: string, id: string): string {
if (user === "guest") throw new Forbidden(`${user} may not read ${id}`);
return findDocument(id);
}
// The one place that turns failures into responses.
export function handleRequest(user: string, id: string): { status: number; body: string } {
try {
return { status: 200, body: readDocument(user, id) };
} catch (error) {
if (error instanceof NotFound) return { status: 404, body: error.message };
if (error instanceof Forbidden) return { status: 403, body: error.message };
return { status: 500, body: "unexpected error" };
}
}A catch only handles what it doesn't rethrow. Narrow it with instanceof and rethrow the rest; the checker follows which kinds go on:
✓ Accepted0 diagnostics
ts
import { type Option, PropagateError } from "@evobug_com/safe-ts-std/result";
export class NotFound extends PropagateError {}
export class Forbidden extends PropagateError {}
function findDocument(user: string, id: string): string {
if (user === "guest") throw new Forbidden(`${user} may not read ${id}`);
if (id === "") throw new NotFound("no id");
return `document ${id}`;
}
// Handles NotFound; Forbidden goes on to the caller, who has to handle it.
export function findIfAny(user: string, id: string): Option<string> {
try {
return findDocument(user, id);
} catch (error) {
if (error instanceof NotFound) return undefined;
throw error;
}
}If nothing catches it, the checker says so:
✕ Rejecteduncaught-propagation
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
class ConfigMissing extends PropagateError {}
function loadConfig(): string {
throw new ConfigMissing("no config file");
}
loadConfig();safe-ts check also prints a map of which functions can throw which errors, and where each one is caught. When many unhandled failures start in the same place, it ends with a count of them by origin (Where to start).
To turn one kind into a Result at a boundary, write the try once in a helper that takes the work as a callback. The callback runs inside the helper's call, so the helper's catch handles it, and every caller gets a Result:
✓ Accepted0 diagnostics
ts
import { err, PropagateError, type Result } from "@evobug_com/safe-ts-std/result";
export class Malformed extends PropagateError {}
function readLength(bytes: Uint8Array): number {
const length = bytes[0];
if (length === undefined) throw new Malformed("empty packet");
return length;
}
function catchMalformed<T>(work: () => T): Result<T, Malformed> {
try {
return work();
} catch (error) {
if (error instanceof Malformed) return err(error);
throw error;
}
}
export function packetLength(bytes: Uint8Array): Result<number, Malformed> {
return catchMalformed(() => readLength(bytes));
}The name of a function works like the arrow that calls it: catchMalformed(readLength) would be followed into catchMalformed just the same, and list.map(readLength) like list.map((b) => readLength(b)). So would a copy (const read = readLength), .call(...) and Reflect.apply(...). A rejection is a throw by another name: return Promise.reject(new Malformed("empty")), or reject(new Malformed("empty")) in a new Promise executor, propagates Malformed like throw in an async function, and rejecting with anything but a PropagateError is no-throw, like throwing it.
Methods reached through fields and declared types
A service usually holds what it uses in fields. The checker follows a method wherever the class is written down one hop away: a field declared with it (as here, a constructor parameter property; also = new Repo() or this.repo = new Repo() in the constructor), a property of a declared type (deps.repo.load(id) with deps: { readonly repo: Repo }), a function declared to return it (makeRepo().load(id), (await openRepo()).load(id)), and a member of a module-level object or of an object literal a readonly field holds (api.users.load(id), this.api.load(id)), across files. Reading a getter (repo.size) or writing a setter runs it, and what it throws goes on from there.
✅ Accepted: what Repo#load throws reaches handle through the field, and is caught there
✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
export class NotFound extends PropagateError {}
class Repo {
load(id: string): string {
if (id === "") throw new NotFound("no id");
return `document ${id}`;
}
}
class Documents {
constructor(private readonly repo: Repo) {}
read(id: string): string {
return this.repo.load(id);
}
}
const documents = new Documents(new Repo());
export function handle(id: string): { status: number; body: string } {
try {
return { status: 200, body: documents.read(id) };
} catch (error) {
if (error instanceof NotFound) return { status: 404, body: error.message };
return { status: 500, body: "unexpected error" };
}
}Without the try, handle would propagate NotFound to its callers, and a call at the top level is uncaught-propagation. A value declared with an interface isn't followed this way: a method an interface declares has no body to look into. Its type says what it can fail with, next.
Handing such a method over by name (queueMicrotask(this.repo.load)) runs it without its object; if it uses this, that is unbound-method.
Failures behind an interface
When the value is declared with an interface (or a base class, or it is a callback taken from a list), the call runs whatever was put there, so the checker can't follow it. The type says what it may throw instead, as a trait method's signature does in Rust: std's Throws<R, E> as the return type (it is R to TypeScript), Throwing<Args, R, E> for a function type. A function type that says nothing can't fail. A call through it propagates what it declares, and failure-contract checks everything put into it: a class that implements the interface, an object literal of it, an override, a callback stored for later.
✅ Accepted: Store.get declares NotFound; the implementation fits, and the caller handles it
✓ Accepted0 diagnostics
ts
import { PropagateError, type Throws } from "@evobug_com/safe-ts-std/result";
export class NotFound extends PropagateError {}
export interface Store {
readonly get: (id: string) => Throws<string, NotFound>;
}
export class MemoryStore implements Store {
private readonly items = new Map<string, string>([["1", "first"]]);
get(id: string): string {
const item = this.items.get(id);
if (item === undefined) throw new NotFound(id);
return item;
}
}
export function handle(store: Store, id: string): { status: number; body: string } {
try {
return { status: 200, body: store.get(id) };
} catch (error) {
if (error instanceof NotFound) return { status: 404, body: error.message };
return { status: 500, body: "unexpected error" };
}
}Written readonly get: (id: string) => string, MemoryStore#get would be a failure-contract: a call through Store would let NotFound out where nothing is told to handle it. An async member declares what it rejects with inside its promise: Promise<Throws<User, NotFound>>. A type alias may stand for it, generic or not, here or imported (type Reply<T> = Promise<Throws<T, NotFound>>, then (id: string) => Reply<User>).
Generators
A generator's body runs when it is stepped, so a function* that throws a PropagateError fails in the loop (or .next() call) that steps it. The checker follows it: the function that calls the generator propagates what its body throws, and a try around creating and stepping it catches it.
✓ Accepted0 diagnostics
ts
import { err, PropagateError, type Result } from "@evobug_com/safe-ts-std/result";
export class BadRow extends PropagateError {}
/** Reads a CSV export of orders, one row at a time. */
function* orders(lines: readonly string[]): Generator<{ id: string; total: number }, void, void> {
for (const line of lines) {
const [id, total] = line.split(",");
const amount = Number(total);
if (id === undefined || id === "" || Number.isNaN(amount)) throw new BadRow(`bad row: ${line}`);
yield { id, total: amount };
}
}
export function revenue(lines: readonly string[]): Result<number, BadRow> {
try {
let total = 0;
for (const order of orders(lines)) total += order.total;
return total;
} catch (error) {
if (error instanceof BadRow) return err(error);
throw error;
}
}The checker counts the throw where the generator is stepped, when every use of it steps it (for...of, .next(), spread, yield*, Array.from): one created before a try and stepped inside it is caught, one created inside a try and stepped after it is not. A generator handed back or passed on counts where it is created.
Methods the language calls for you
Some methods run without a call in the source naming them: toString in a template or String(x), valueOf in a < b, toJSON in JSON.stringify, [Symbol.iterator] in for...of, [Symbol.dispose] at the end of a using block, then in await. A failure there reaches the code around with no caller told, so implicit-propagation refuses such a method that can propagate a PropagateError, where it is defined: keep it total, and put what can fail in a method the caller names (format(): Result<string, PriceError>, or a generator method like orders above for an iteration that may fail). What the source does name without parentheses is followed: a tagged template's tag, a decorator, a getter read off a value whose class is written down (also destructured, const { total } = order).
When catching everything is right: harness boundaries
A catch that handles every error and rethrows nothing usually hides a bug: the failure nobody planned for. It is right in one place: a harness that runs independent pieces of work and reports on each, like a test runner, a linter running its checks, or a queue running jobs. There, "this one failed" is the answer. A bug in one check should fail that check and let the others run, and nothing above the harness knows better what to do with it, so there is nothing to rethrow. The checker counts a catch without a rethrow as handling every kind, wherever it is, so it accepts this one; whether a catch-all belongs there is your call.
✓ Accepted0 diagnostics
ts
import { describeError, type Option, PropagateError } from "@evobug_com/safe-ts-std/result";
export class InvalidInvoice extends PropagateError {}
type Invoice = { readonly lines: readonly number[]; readonly total: number };
type Outcome = { readonly check: string; readonly failure: Option<string> };
function checkTotal(invoice: Invoice): void {
const sum = invoice.lines.reduce((a, b) => a + b, 0);
if (sum !== invoice.total) throw new InvalidInvoice(`the lines add up to ${sum}, not ${invoice.total}`);
}
/** Runs one check of the invoice linter. Whatever it throws fails this check only. */
function runCheck(check: string, run: () => void): Outcome {
try {
run();
return { check, failure: undefined };
} catch (error) {
return { check, failure: describeError(error) };
}
}
export function lint(invoice: Invoice): Outcome[] {
return [
runCheck("the total adds up", () => checkTotal(invoice)),
runCheck("it has lines", () => {
if (invoice.lines.length === 0) throw new InvalidInvoice("no lines");
}),
];
}Keep the catch-all at the top, around one unit of work at a time, and report what it caught rather than dropping it. Everywhere below it, catch by kind with instanceof and rethrow the rest, as in the sections above.
When you call code that throws
Built-ins such as JSON.parse, new URL and decodeURIComponent can throw. So can some libraries and your own legacy code. Calling them unprotected is reported:
✕ Rejectedunhandled-failure
ts
export function host(url: string): string {
return new URL(url).host;
}unsafe(() => ...) catches the throw and gives you a Result. (unsafeAsync does the same for promises.) Its error has type unknown, because JavaScript can throw anything, so turn it into a named error right at the call:
✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result, unsafe } from "@evobug_com/safe-ts-std/result";
export type UrlError = Enum<{ Invalid: { url: string } }>;
export const UrlError = constructors<UrlError>();
export function host(url: string): Result<string, UrlError> {
const parsed = unsafe(() => new URL(url));
if (isErr(parsed)) return err(UrlError.Invalid({ url }));
return parsed.host;
}ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result, unsafe } from "@evobug_com/safe-ts-std/result";
export type UrlError = Enum<{ Invalid: { url: string } }>;
export const UrlError = constructors<UrlError>();
export function host(url: string): Result<string, UrlError> {
const parsed = unsafe(() => new URL(url));
if (isErr(parsed)) return err(({ tag: "Invalid", url } satisfies UrlError as UrlError));
return parsed.host;
}✅ Also accepted: try/catch, when the try holds only the call that throws
✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";
export type UrlError = Enum<{ Invalid: { url: string } }>;
export const UrlError = constructors<UrlError>();
export function host(url: string): Result<string, UrlError> {
try {
return new URL(url).host;
} catch {
return err(UrlError.Invalid({ url }));
}
}ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";
export type UrlError = Enum<{ Invalid: { url: string } }>;
export const UrlError = constructors<UrlError>();
export function host(url: string): Result<string, UrlError> {
try {
return new URL(url).host;
} catch {
return err(({ tag: "Invalid", url } satisfies UrlError as UrlError));
}
}Better still, use an API that doesn't throw: parseJson<T> instead of JSON.parse, a pack's safe version, zod's safeParse instead of parse.
However the call is written, it is the same call: JSON["parse"](text), const { parse } = JSON; parse(text), JSON.parse.call(JSON, text) and globalThis.JSON.parse(text) are reported like JSON.parse(text), and texts.map(decodeURIComponent) like texts.map((t) => decodeURIComponent(t)). A function used by name has no call here to wrap, so handle the failure in a function you pass instead (unhandled-failure).
The value unsafe gives back has the call's type, except any: a function returning any (JSON.parse, response.json(), an untyped library) gives unknown, so unsafe(() => JSON.parse(text)) is a Result<unknown, unknown> and the value is checked (validate<T>) before it is used. That is what parseJson<T>(text) does in one call.
Around a function that already returns a Result, its typed Err and the throw would merge into one Err<unknown>. Pass Panic to keep them apart: the throw (a bug) becomes a Panic, which is not an Err, and the returned Err keeps its type:
✓ Accepted0 diagnostics
ts
import { isErr, isPanic, Panic, type Result, unsafeAsync } from "@evobug_com/safe-ts-std/result";
declare function send(message: string): Promise<Result<void, "refused">>;
export async function deliver(message: string): Promise<string> {
const sent = await unsafeAsync(() => send(message), Panic);
if (isPanic(sent)) return `bug: ${String(sent.reason)}`;
if (isErr(sent)) return `not delivered: ${sent.error}`; // sent.error: "refused"
return "delivered";
}Don't turn a bug into an Err. unsafe and unsafeAsync are for code that throws by design: built-ins, libraries, legacy code. Around your own code, a throw is a bug, and unsafeAsync(() => search(text)) without Panic makes it a failure like any other: the page shows "Search failed" as a toast, and nobody learns about the bug. Pass Panic there, as above, and send the Panic where bugs go (the error reporter, a generic "something went wrong"), apart from the Errs the user can act on. Or leave the throw alone: a task whose function rejects is a bug too, and useTask treats it as one (its run rejects). The idiomatic rule unsafe-project-call reports unsafe without Panic around the project's own checked code.
panic is for invariants. panic(...) stops the program, for a condition no input can cause: a table the code itself defines with a name listed twice (panic). A value that isn't there yet is not one. A store read before its first response arrived is loading, and a panic there crashes the page that should show "Loading…". Give the waiting a value instead: an AsyncState, or an Option the page tests. panic-on-loading (idiomatic) reports a panic under a loading flag.
What the rules catch in practice
Two kinds of report found real bugs while a large app was adopting SAFE-TS. Both were quick to fix, because the report prints the whole path from the call to the throw.
A render loop that stops for good. A frame callback that lets an error escape never schedules the next frame, so the screen freezes and nothing says why. Here a basket holding a product the price list lacks does it:
✕ Rejecteduncaught-propagation
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
export class UnknownProduct extends PropagateError {}
const prices = new Map([["tea", 4], ["cake", 6]]);
function price(product: string): number {
const found = prices.get(product);
if (found === undefined) throw new UnknownProduct(product);
return found;
}
function draw(canvas: CanvasRenderingContext2D, basket: readonly string[]): void {
canvas.fillText(`total: ${basket.reduce((sum, p) => sum + price(p), 0)}`, 10, 20);
}
export function start(canvas: CanvasRenderingContext2D, basket: readonly string[]): void {
const frame = () => {
draw(canvas, basket);
requestAnimationFrame(frame);
};
requestAnimationFrame(frame);
}The path in the report is start/frame → draw → price → throw new UnknownProduct. Catch per frame, so one bad frame shows a message and the loop goes on. A library's ticker can stop the same way: PixiJS's stops calling its callbacks after one throws.
✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
export class UnknownProduct extends PropagateError {}
const prices = new Map([["tea", 4], ["cake", 6]]);
function price(product: string): number {
const found = prices.get(product);
if (found === undefined) throw new UnknownProduct(product);
return found;
}
function draw(canvas: CanvasRenderingContext2D, basket: readonly string[]): void {
canvas.fillText(`total: ${basket.reduce((sum, p) => sum + price(p), 0)}`, 10, 20);
}
export function start(canvas: CanvasRenderingContext2D, basket: readonly string[]): void {
const frame = () => {
try {
draw(canvas, basket);
} catch (error) {
if (!(error instanceof UnknownProduct)) throw error;
canvas.fillText(`unknown product: ${error.message}`, 10, 20);
}
requestAnimationFrame(frame);
};
requestAnimationFrame(frame);
}A computed that throws for data the app didn't expect. Vue calls a computed when something reads it, from a render or a watcher, where nothing of yours catches. An order status the server added later is enough:
✕ Rejecteduncaught-propagation
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
import { computed, type ComputedRef, type Ref } from "vue";
export class UnknownStatus extends PropagateError {}
function describe(status: string): string {
if (status === "paid") return "Paid, thank you";
if (status === "shipped") return "On its way";
throw new UnknownStatus(status);
}
export function useStatusLabel(status: Readonly<Ref<string>>): ComputedRef<string> {
return computed(() => describe(status.value));
}Give the status a type that holds the values the app doesn't know yet. An Open<K> read with parseJson or validate is one of the listed strings or Unknown, and match decides what each one shows. Nothing throws:
✓ Accepted0 diagnostics
ts
import { match } from "@evobug_com/safe-ts-std/enum";
import type { Open } from "@evobug_com/safe-ts-std/open";
import { computed, type ComputedRef, type Ref } from "vue";
// Read from the server with `validate`: a status added later is `Unknown`.
export type OrderStatus = Open<"paid" | "shipped">;
export function useStatusLabel(status: Readonly<Ref<OrderStatus>>): ComputedRef<string> {
return computed(() =>
match(status.value, {
paid: () => "Paid, thank you",
shipped: () => "On its way",
Unknown: ({ value }) => `Status: ${value}`,
}),
);
}✅ Also accepted: a try inside the computed, when the code that throws isn't yours to change
✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
import { computed, type ComputedRef, type Ref } from "vue";
export class UnknownStatus extends PropagateError {}
function describe(status: string): string {
if (status === "paid") return "Paid, thank you";
if (status === "shipped") return "On its way";
throw new UnknownStatus(status);
}
export function useStatusLabel(status: Readonly<Ref<string>>): ComputedRef<string> {
return computed(() => {
try {
return describe(status.value);
} catch (error) {
if (error instanceof UnknownStatus) return `Status: ${error.message}`;
throw error;
}
});
}must-use-result found the third kind: a call that returns a Result written as a statement in a test, so its failure was never looked at.
Why not throw everything? Throwing is slow when failure is common
Creating an error records a stack trace, and jumping to a catch isn't free either (v8.dev). A Result is a plain value. When failing is common, as with validating input, the difference is large:
✅ Accepted: failure by throwing
✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
class NotAPort extends PropagateError {}
function parsePort(text: string): number {
const n = Number(text);
if (!Number.isInteger(n)) throw new NotAPort(`not a port: ${text}`);
return n;
}
export function countValid(inputs: readonly string[]): number {
let ok = 0;
for (const input of inputs) {
try {
parsePort(input);
ok++;
} catch {
// not a port
}
}
return ok;
}✅ Accepted: failure as a value
✓ Accepted0 diagnostics
ts
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
function parsePort(text: string): Result<number, string> {
const n = Number(text);
if (!Number.isInteger(n)) return err(`not a port: ${text}`);
return n;
}
export function countValid(inputs: readonly string[]): number {
let ok = 0;
for (const input of inputs) if (!isErr(parsePort(input))) ok++;
return ok;
}Benchmark
countValid(inputs)Code that runs
Each version runs on its own, in a fresh copy of this code (TypeScript types are removed first). The setup runs once per version; the last line is what is timed.
throw
import { PropagateError } from "@evobug_com/safe-ts-std/result";
class NotAPort extends PropagateError {}
function parsePort(text: string): number {
const n = Number(text);
if (!Number.isInteger(n)) throw new NotAPort(`not a port: ${text}`);
return n;
}
export function countValid(inputs: readonly string[]): number {
let ok = 0;
for (const input of inputs) {
try {
parsePort(input);
ok++;
} catch {
// not a port
}
}
return ok;
}Result
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
function parsePort(text: string): Result<number, string> {
const n = Number(text);
if (!Number.isInteger(n)) return err(`not a port: ${text}`);
return n;
}
export function countValid(inputs: readonly string[]): number {
let ok = 0;
for (const input of inputs) if (!isErr(parsePort(input))) ok++;
return ok;
}Setup and timed expression
const inputs = Array.from({ length: 1000 }, (_, i) => (i % 2 ? String(i) : "x" + i));
// timed:
countValid(inputs); Warm: median time per run once V8 has optimized the code (p10–p90: the spread of the samples). First run: the very first call, before any optimization, which is closer to code that runs rarely. Measured in a Web Worker in your browser; results depend on the engine and the machine, which is the point of running it here.
Size: throw 478 B (286 B gzip) · Result 397 B (245 B gzip).
Measured on Node 26 with half the inputs invalid: 2.2 ms per thousand inputs when throwing, 16 µs with Result. Throwing is still the right tool for a PropagateError, which ends the whole operation: that happens rarely.
q(...) and using
q(...) becomes a plain return, so like any early return it runs [Symbol.dispose] for the using declarations in the function it returns from.
Rules in this guide: no-throw, unhandled-failure, must-use-result, uncaught-propagation, q-position, q-needs-result-return, q-undeclared-error