unhandled-failure
A call that can throw is not handled.
Why: the throw escapes into code that doesn't expect it. Reported for the language's built-ins that can throw for a value their types allow, from a map of every one of them (The language's built-ins): on bad input (JSON.parse, new RegExp, decodeURIComponent, BigInt, Uint8Array.fromBase64, Temporal.PlainDate.from), on the receiver's state (list.reduce(f) of a list that may be empty, toISOString of a date parsed from text, also through Date.parse or a function that returns one, a DataView read past its end), on an argument that comes from data (n.toFixed(digits), " ".repeat(width - text.length), String.fromCodePoint(code), new Array(count), a locale or time zone given to Intl or toLocaleString), and for bigint /, % and **; for the web globals Node and browsers share (new URL, btoa, atob, structuredClone); for functions in other files that can throw (with the full path to where), and for library calls: what automatic mode finds in the library's code (the message says the kind, e.g. (zod, found in its code: argument check)), or what a feature pack declares, also for globals: the Node and browser packs report fetch(), localStorage.setItem(), response.json(), crypto.subtle.*() and more, with the exact error, and replace the built-in check of the globals they list (globals). Not reported: test runners' hooks and assertions (beforeAll(...), expect(x).toBe(y), assert.fail() of Vitest, Jest, Mocha or Chai), which throw only when misused or to fail the test (test runners). Guide: Errors.
✕ Rejectedunhandled-failure
ts
export function decode(component: string): string {
return decodeURIComponent(component);
}✓ Accepted0 diagnostics
ts
import { isErr, unsafe } from "@evobug_com/safe-ts-std/result";
export function decode(component: string): string {
const decoded = unsafe(() => decodeURIComponent(component));
return isErr(decoded) ? component : decoded;
}A built-in is recognized by what the name is bound to, not by the name alone. atob imported from a pack (import { atob } from "@evobug_com/safe-ts-feature-browser/encoding", which returns a Result), or a function or object of your own named atob or JSON, is judged like any other call. Node's own export of a global is the global: URL from node:url, atob from node:buffer, TextDecoder from node:util.
✓ Accepted0 diagnostics
ts
import { atob } from "@evobug_com/safe-ts-feature-browser/encoding";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { mapErr, type Result } from "@evobug_com/safe-ts-std/result";
export type DecodeError = Enum<{ NotBase64: {} }>;
export const DecodeError = constructors<DecodeError>();
export function decodeBase64(text: string): Result<string, DecodeError> {
return mapErr(atob(text), () => DecodeError.NotBase64());
}ts
import { atob } from "@evobug_com/safe-ts-feature-browser/encoding";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { mapErr, type Result } from "@evobug_com/safe-ts-std/result";
export type DecodeError = Enum<{ NotBase64: {} }>;
export const DecodeError = constructors<DecodeError>();
export function decodeBase64(text: string): Result<string, DecodeError> {
return mapErr(atob(text), () => ({ tag: "NotBase64" } satisfies DecodeError as DecodeError));
}A call is a call however it is spelled: JSON["parse"](text), (JSON).parse(text), globalThis.JSON.parse(text), a copy (const read = JSON.parse; read(text), const { parse } = JSON, const J = JSON; J.parse(text)), JSON.parse.call(JSON, text), .apply(...), .bind(...)(...), Reflect.apply(JSON.parse, JSON, [text]) and Reflect.construct(URL, [text]) are all reported. A function used by name is the arrow that calls it, so parts.map(decodeURIComponent) is reported where decodeURIComponent is written, as parts.map((p) => decodeURIComponent(p)) is, and so is a built-in stored by name ([JSON.parse], { read: JSON.parse }). A copy another file exports (export const parseText = JSON.parse, export const J = JSON, export const storage = localStorage, also renamed or re-exported) is followed to the calls made through it there, and a readonly field holding one (private readonly parse = JSON.parse) to this.parse(text): the call is reported, inside a try it is handled. A copy that can't be followed from where it is called counts where it is made: exported destructured (export const { parse } = JSON), a let set again, a field that isn't readonly, and a readonly one other files can reach (public, protected or static, which also counts at the calls in its class):
✕ Rejectedunhandled-failure
ts
export function read(text: string): unknown {
const { parse } = JSON;
return parse(text);
}
export function decodeAll(parts: readonly string[]): readonly string[] {
return parts.map(decodeURIComponent);
}ts
export function read(text: string): unknown {
const { parse } = JSON;
return parse(text);
}
export function decodeAll(parts: readonly string[]): readonly string[] {
{ const __la1 = parts; const __lf1_0: any = decodeURIComponent; if (typeof __lf1_0 !== "function") throw new TypeError(`${typeof __lf1_0} is not a function`); const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { __lr1[__li1] = __lf1_0(__le1, __li1, __la1); }} return __lr1; }
}Wrapping the name (parts.map(unsafe(() => decodeURIComponent))) would hand map a Result instead of the function, so no quick fix is offered there: decode in a function that handles the failure.
✓ 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 DecodeError = Enum<{ Malformed: { part: string } }>;
export const DecodeError = constructors<DecodeError>();
export function decodeAll(parts: readonly string[]): Result<readonly string[], DecodeError> {
const decoded: string[] = [];
for (const part of parts) {
const text = unsafe(() => decodeURIComponent(part));
if (isErr(text)) return err(DecodeError.Malformed({ part }));
decoded.push(text);
}
return decoded;
}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 DecodeError = Enum<{ Malformed: { part: string } }>;
export const DecodeError = constructors<DecodeError>();
export function decodeAll(parts: readonly string[]): Result<readonly string[], DecodeError> {
const decoded: string[] = [];
for (const part of parts) {
const text = unsafe(() => decodeURIComponent(part));
if (isErr(text)) return err(({ tag: "Malformed", part } satisfies DecodeError as DecodeError));
decoded.push(text);
}
return decoded;
}The failure travels across files. If config.ts calls JSON.parse unprotected, every caller of its function is told, with the path:
error[unhandled-failure]: `readConfig` can throw, but the failure is not handled
= help: Failure path: readConfig → JSON.parse() at config.ts:4:18safe-ts check --json gives the same as data: "path": ["readConfig"] and "origin": "JSON.parse() at config.ts:4:18" (JSON output). When findings share an origin, safe-ts check ends with a count of them by origin, so you can fix the place many come from first (Where to start).
JSON.stringify throws only for what its argument holds: a cycle, a BigInt, or a toJSON or getter that throws. It isn't reported when the argument's type says it can't hold any of those: strings, numbers, booleans, and objects, arrays, tuples, Records, Options and unions of them. The type is found the way parseJson<T> finds T: through type aliases and interfaces, in this file or imported (also re-exported), namespace members (Backend.Models.User, also global ones, see namespaces), Record, Partial, Pick, mapped and conditional types (DeepPartial<Settings>), and indexed ones (Options["mode"]). The argument can be a literal, a binding with a declared type, a member of one (this.items with readonly items: Product[], order.total, this.options.pageSize), what it was destructured from (const { id, total } = order), an item a callback or a for…of gets (Object.entries(prices).map(([sku]) => ...)), the array an array's .map, .flatMap or .filter returns, or Array.from(x, f) (what the callback is declared to return, or else what its body returns: rows.map((r): string => r.id), Object.entries(r).map(([id]) => id)), a string method's result (title.slice(0, 20)), map.get(key) and map.size of a Map type, Object.fromEntries(map), Object.freeze({ ... }), what a function or method is declared to return (also an arrow function bound to a const), a value after typeof x === "string", or a Result after if (isErr(r)) return .... The type is taken at its word: a value with extra properties it doesn't mention isn't seen.
✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";
type Address = { street: string; city: string };
type Order = { id: string; total: number; shipTo: Option<Address>; tags: Record<string, string[]> };
export class Checkout {
readonly orders: Order[] = [];
save(): string {
return JSON.stringify(this.orders);
}
summary(stock: Map<string, number>): string {
const { id, total } = this.orders[0] ?? { id: "", total: 0 };
return JSON.stringify({ id, total, left: stock.get(id), kinds: stock.size });
}
ids(): string {
return JSON.stringify(this.orders.map((order) => [order.id, order.total]));
}
}Still reported, and the message says why: a bigint, unknown or JsonValue (each can hold a cycle), a type that refers to itself (type Category = { children: Category[] }: a value can contain itself), a field named toJSON, and a replacer function, which runs for every value and may throw or return what can't be written. A value the code doesn't type (an untyped let, a package's return value, [] that grows later) is reported too.
❌ Rejected: `JSON.stringify()` can throw, but the failure is not handled: a `JsonValue` can hold a cycle
✕ Rejectedunhandled-failure
ts
import type { JsonValue } from "@evobug_com/safe-ts-std/json";
export function body(payload: JsonValue): string {
return JSON.stringify(payload);
}new RegExp(pattern, flags) throws for a pattern that doesn't parse, or bad flags. It isn't reported with literal flags and a pattern that can't be wrong: a literal that parses, a RegexSource (what escapeRegExp(text) from @evobug_com/safe-ts-std/regexp returns, or a value declared with that type, also in another file), or a pattern built only from those parts, constant text and numbers: in a template, joined with +, or with .join(sep) of an array literal, of words.map(escapeRegExp) or of a RegexSource[]. The pattern is checked by parsing it with every kind of text the parts can bring (escaped text: a letter, an escape or nothing; a number: 0, -1.5e-7, NaN, Infinity; a joined list: one item and two), so `x{${n}}` with the u flag, and words.map(escapeRegExp).join(")("), are still reported. Text put in unescaped is reported, with the reason: new RegExp(`${text}`) as much as new RegExp(text), and a string[] joined. (Inside a test's callback, a throw just fails the test, so nothing is reported there either way.)
✓ Accepted0 diagnostics
ts
import { escapeRegExp } from "@evobug_com/safe-ts-std/regexp";
const PREFIX = "INV-";
export function invoiceLine(customer: string, page: number, pages: number): RegExp {
return new RegExp(`^${PREFIX}\\d+ ${escapeRegExp(customer)} \\(${page} of ${pages}\\)$`, "u");
}
export function anyOf(words: readonly string[]): RegExp {
return new RegExp("^(?:" + words.map(escapeRegExp).join("|") + ")$", "i");
}ts
import { escapeRegExp } from "@evobug_com/safe-ts-std/regexp";
const PREFIX = "INV-";
export function invoiceLine(customer: string, page: number, pages: number): RegExp {
return new RegExp(`^${PREFIX}\\d+ ${escapeRegExp(customer)} \\(${page} of ${pages}\\)$`, "u");
}
export function anyOf(words: readonly string[]): RegExp {
return new RegExp("^(?:" + (() => { const __la1 = words; const __lf1_0: any = escapeRegExp; if (typeof __lf1_0 !== "function") throw new TypeError(`${typeof __lf1_0} is not a function`); const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { __lr1[__li1] = __lf1_0(__le1, __li1, __la1); }} return __lr1.join("|"); })() + ")$", "i");
}❌ Rejected: …: text put into the pattern isn't escaped
✕ Rejectedunhandled-failure
ts
export function startsWith(label: string): RegExp {
return new RegExp(`^${label}: `);
}btoa and ASCII
btoa(text) throws for a character above U+00FF. It isn't reported when the text can't hold one: written text without such a character, String(n) or a template of numbers, bigints and booleans (btoa(`Page:${id}`)), and an Ascii, from isAscii(text) (which narrows) or asciiOf(n), or declared with that type. A function that only encodes such values doesn't fail either, so its callers aren't reported. A string that may hold anything is still reported.
✓ Accepted0 diagnostics
ts
import { isAscii } from "@evobug_com/safe-ts-std/ascii";
import type { Option } from "@evobug_com/safe-ts-std/result";
export function issuePath(id: number): string {
return `/issues/${btoa(`Issue:${id}`)}`;
}
export function slugPath(slug: string): Option<string> {
return isAscii(slug) ? `/pages/${btoa(slug)}` : undefined;
}✕ Rejectedunhandled-failure
ts
export function namePath(name: string): string {
return `/people/${btoa(name)}`;
}new URL(path, import.meta.url) isn't reported when path is text (a literal, or a const) that names a path, ./worker.ts, assets/, ../data/table.json or /x: resolved against the module's own URL it always gives a URL. A URL of its own (https:x, //cdn.example/x) can fail. For the same reason fileURLToPath(new URL("./src", import.meta.url)) and fileURLToPath(import.meta.url) (from node:url) aren't reported: a module loaded from a file has a file: URL, and so does a path resolved against it.
✓ Accepted0 diagnostics
ts
import { fileURLToPath } from "node:url";
export const srcDir = fileURLToPath(new URL("src", import.meta.url));
export const worker = new URL("./worker.ts", import.meta.url);A helper that takes the path as a parameter (here(relative)) can't be checked: there path may be anything. Write the calls out, or on Node 20.11 and later use import.meta.dirname and import.meta.filename, which are paths already and need no conversion: path.join(import.meta.dirname, "src").
encodeURIComponent and encodeURI throw only for text holding a lone surrogate (half of a UTF-16 pair), and decodeURIComponent and decodeURI only for a % not followed by two hex digits, or escaped bytes that aren't UTF-8. For text written as a string literal, a template without substitutions, or a const bound to one, that is decided from the text:
✓ Accepted0 diagnostics
ts
const SEARCH_PATH = "/search results";
export const searchUrl = `${encodeURI(SEARCH_PATH)}?q=${encodeURIComponent("a&b")}`;
export const title = decodeURIComponent("caf%C3%A9");❌ Rejected: %E2%82 is two bytes of a three-byte character
✕ Rejectedunhandled-failure
ts
export const euro = decodeURIComponent("%E2%82");btoa throws only for a character above U+00FF. Text written out without one can't make it throw, and neither can numbers written as text: String(n), n.toString(), n.toFixed(2), or a template made of those and text (`${id}:${page}`), where n, id and page are declared as numbers (in this file or another). Anything else is reported, with std's toBase64 in the help: it encodes any text as UTF-8 and can't fail. For atob the help names fromBase64, which returns a Result. See base64.
✓ Accepted0 diagnostics
ts
export function pathOf(id: number, page: number): string {
return `/issues/${btoa(String(id))}/${btoa(`${id}:${page}`)}`;
}❌ Rejected: a string may hold any character
✕ Rejectedunhandled-failure
ts
export const encode = (name: string): string => btoa(name);A function's failures are what can happen during a call to it. The methods of an object it returns, and callbacks it hands to a timer or a listener, run later: a failure in them is reported where it is, not at every call of the function that made them.
A try counts as handling. For promises it must await inside the try:
✓ Accepted0 diagnostics
ts
import { readFile } from "node:fs/promises";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";
import type { SafePath } from "@evobug_com/safe-ts-std/path";
export type ReadError = Enum<{ Unreadable: { path: string; cause: unknown } }>;
export const ReadError = constructors<ReadError>();
export async function readText(path: SafePath): Promise<Result<string, ReadError>> {
try {
return await readFile(path, "utf8");
} catch (cause) {
return err(ReadError.Unreadable({ path, cause }));
}
}ts
import { readFile } from "node:fs/promises";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";
import type { SafePath } from "@evobug_com/safe-ts-std/path";
export type ReadError = Enum<{ Unreadable: { path: string; cause: unknown } }>;
export const ReadError = constructors<ReadError>();
export async function readText(path: SafePath): Promise<Result<string, ReadError>> {
try {
return await readFile(path, "utf8");
} catch (cause) {
return err(({ tag: "Unreadable", path, cause } satisfies ReadError as ReadError));
}
}✕ Rejectedunhandled-failure
ts
import { readFile } from "node:fs/promises";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";
import type { SafePath } from "@evobug_com/safe-ts-std/path";
export type ReadError = Enum<{ Unreadable: { path: string; cause: unknown } }>;
export const ReadError = constructors<ReadError>();
export async function readText(path: SafePath): Promise<Result<string, ReadError>> {
try {
return readFile(path, "utf8");
} catch (cause) {
return err(ReadError.Unreadable({ path, cause }));
}
}ts
import { readFile } from "node:fs/promises";
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";
import type { SafePath } from "@evobug_com/safe-ts-std/path";
export type ReadError = Enum<{ Unreadable: { path: string; cause: unknown } }>;
export const ReadError = constructors<ReadError>();
export async function readText(path: SafePath): Promise<Result<string, ReadError>> {
try {
return readFile(path, "utf8");
} catch (cause) {
return err(({ tag: "Unreadable", path, cause } satisfies ReadError as ReadError));
}
}Inside an async function, a call that throws (or a rejection it awaits or returns) rejects the function's promise instead. When that function is the module's own (not exported, and only ever called, never passed around as a value) and every call of it handles the rejection (await unsafeAsync(() => decode(token)), .catch(...), awaited in a try that handles everything), the call inside it isn't reported: it is handled where the promise is. Otherwise it is reported where it fails, and the help says that handling the rejection at every call does too.
✅ Accepted: the only call of decodeToken handles its rejection
✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { mapErr, type Result, unsafeAsync } from "@evobug_com/safe-ts-std/result";
export type TokenError = Enum<{ Malformed: {} }>;
export const TokenError = constructors<TokenError>();
async function decodeToken(token: string): Promise<string> {
return atob(token);
}
export async function readToken(token: string): Promise<Result<string, TokenError>> {
return mapErr(await unsafeAsync(() => decodeToken(token)), () => TokenError.Malformed());
}ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { mapErr, type Result, unsafeAsync } from "@evobug_com/safe-ts-std/result";
export type TokenError = Enum<{ Malformed: {} }>;
export const TokenError = constructors<TokenError>();
async function decodeToken(token: string): Promise<string> {
return atob(token);
}
export async function readToken(token: string): Promise<Result<string, TokenError>> {
return mapErr(await unsafeAsync(() => decodeToken(token)), () => ({ tag: "Malformed" } satisfies TokenError as TokenError));
}The language's built-ins
A built-in that can throw isn't reported where what is written shows it can't: an initial value for reduce (or a list known to have an element), a date from the clock or checked with Number.isNaN(date.getTime()), an argument written in the code (n.toFixed(2), BigInt(1), new Intl.DateTimeFormat("en", { timeZone: "UTC" })), one checked against the range just before (if (digits < 0 || digits > 100) return ...;), or one the function computes itself rather than receives. An argument that comes from data (a parameter, what is read off one, parsed text) is reported; so is a literal the checker knows to be wrong (n.toFixed(101), a time zone that doesn't exist). The message names the condition and what to write: an initial value, a check of the date, padStart instead of repeat for padding, a check of the divisor. The definitions, every built-in's condition and what was narrowed after an adopter's code are in The language's built-ins.
✕ Rejectedunhandled-failure
ts
export function average(scores: readonly number[]): number {
return scores.reduce((a, b) => a + b) / scores.length;
}
export function per(total: bigint, parts: bigint): bigint {
return total / parts;
}✓ Accepted0 diagnostics
ts
export function average(scores: readonly number[]): number {
if (scores.length === 0) return 0;
return scores.reduce((a, b) => a + b) / scores.length;
}
export function per(total: bigint, parts: bigint): bigint {
return parts === 0n ? 0n : total / parts;
}
export function price(amount: number): string {
return amount.toFixed(2);
}Quick fixes: a feature pack's own fix first (e.g. Use safeParse), then Use the safe version where the pack has one (readFileSync(p) becomes the Node pack's readFileSync(p), stmt.run(x) becomes run(stmt, x), with the import), offered where a Result fits: as the value of a const without a type annotation, or with q(...) in a function returning Result<T, unknown> (the quick fix), then Wrap in unsafe(() => …) (unsafeAsync when awaited), Propagate the error with q(unsafe(…)) (in functions returning Result<T, unknown>), Wrap in try/catch (for statements).
What the rule can't see: a built-in's method on a receiver whose type the code doesn't say (a value from an untyped package, a function's result that isn't declared nor plain), a typed array's length or a date made from a number (not reported, why), a DataView whose length a helper checks, a bound kept by a function the argument is computed in; method calls whose receiver's class the source doesn't write down one hop away (a parameter typed with an interface or a union, a generic type, an element of an array or a Map), an override in a subclass when the value is declared as the base class, and library API that is built at runtime (methods installed under computed names) when no feature pack describes it. A function of yours used by name is followed where the arrow standing for it would be: not when it is stored in an object or array literal written inside a function and called through it, or picked in an argument (apply(strict ? find : lookup)); a built-in used by name is reported wherever it is. The safe answers that read a call's arguments (decodeURI("%41"), JSON.stringify of plain data, btoa of ASCII) need the arguments written in the call, so JSON.stringify.call(JSON, data) and values.map(JSON.stringify) are reported, and so is a call through a copy another file made. Not seen: a member chain through such a copy (store.J.parse(text) after import * as store), and the default export of a project file holding one. A callback written as an argument is followed into the function it is handed to, as for uncaught-propagation.