Declarative, retryable error handling for TypeScript, inspired by Rust's Result.
import { safe } from "xerror-js";
const team = await safe(fetchUser(id)) // a Result<User>: it never throws
.andThen((user) => safe(fetchTeam(user.teamId))) // a next step that can fail too
.map((team) => team.name) // transform the value
.inspectErr((error) => console.error(error.message)) // look at the first failure
.unwrapOr("No team"); // or fall back- Rust's
Result.map,andThen,unwrapOr… by the names Rust gives them, each step on its own line, on a promise as on a value. - A unified interface behind one function. Calls, promises, sync or async:
safetells them apart and its return type follows. A sync call gives aResultat once, an async one a promise of aResult. - Never rejects. What a
safepromise holds is aResult, so a failure can't slip past as an unhandled rejection or an untypedcatch (e). - Retries in one line. Exponential backoff with a cap, written in full or as
"3x/500ms/2/5s". - Your own error types.
createSafemakes asafewhose errors areHttpError,DbError… - Zero dependencies, any runtime. Node ≥ 20, Cloudflare Workers and browsers. ESM, ES2022, no runtime globals assumed.
pnpm add xerror-js # or: npm i xerror-js / yarn add xerror-js / bun add xerror-jsCode written in try/catch blocks is hard to reason about: the logic lives in one place and
its error handling in another. The catch can't tell which line threw, and what it catches is
unknown.
// Before: which call failed?
try {
const user = await fetchUser(id);
const orders = await fetchOrders(user.id);
console.log(orders.length);
} catch (error) {
console.error(error); // unknown
}With safe, a failure is a value, handled on the line that caused it, so the code reads top to
bottom, line by line:
// After: each line says what it does when it fails
const user = await safe(fetchUser(id));
if (user.isErr()) return console.error("No user:", user.err().message);
const orders = await safe(fetchOrders(user.unwrap().id));
if (orders.isErr()) return console.error("No orders:", orders.err().message);
console.log(orders.unwrap().length);safe takes a promise, or a function, and its return type follows what you give it:
| You write | You get |
|---|---|
safe(() => JSON.parse(text)) |
Result<any>, at once |
safe(() => total(cart)) |
Result<number>, at once |
safe(save(row)) |
SafePromise<Row>: awaited, a Result |
safe(() => save(row)) |
SafePromise<Row>, also catching a throw before the promise exists |
safe(() => save(row), policy) |
SafePromise<Row>, trying again as the policy says |
Pass the promise when nothing in save(row) can throw before the promise exists, as the
argument is evaluated before safe is entered. Pass a function otherwise, or to wrap several
statements:
const saved = await safe(db.insert(row)); // a promise: settled
const report = await safe(async () => {
// a block: run and settled
const rows = await db.select(query);
return summarize(rows);
});A Result<T, E> holds a value T or an error E (an Error unless you choose otherwise). Its
methods are Rust's, in camelCase:
is_err is isErr(), unwrap_or is unwrapOr().
const order = await safe(placeOrder(cart));
if (order.isErr()) {
metrics.increment("order.failed");
return { status: 500, message: order.err().message };
}
return { status: 201, body: order.unwrap() };Where a failure should just propagate, unwrap a SafePromise in one step:
const user = await safe(fetchUser(id)).expect("loading the user"); // a User, or it throwsAnything thrown that is not an Error is wrapped in one, keeping the original as its cause, so
err().message is always safe to read: throw "boom" → Error("boom").
Give safe a function and a retry policy, and it calls the function again after each failure,
waiting longer each time. Its Result is the first success, or the last failure.
const user = await safe(() => fetchUser(id), {
maximumAttempts: 3, // attempts in all, the first included: 1 never retries
initialInterval: "500ms", // the wait after the first failure
backoffCoefficient: 2, // each wait is the one before × this: 2 doubles, 1 keeps it
maximumInterval: "5s", // the longest a wait grows to
});The same policy, as a shorthand, the x read as "times":
const user = await safe(() => fetchUser(id), "3x/500ms/2/5s");
// │ │ │ └─ never wait longer than 5s (maximumInterval)
// │ │ └─ double the wait each time (backoffCoefficient)
// │ └─ wait 500ms after the 1st failure (initialInterval)
// └─ try 3 times in all (maximumAttempts)The wait after failure n is initial × coefficient^(n − 1), capped at maximum. For
"5x/500ms/2/1.5s":
| Attempt fails | Wait before the next |
|---|---|
| 1st | 500 × 2⁰ = 500 ms |
| 2nd | 500 × 2¹ = 1,000 ms |
| 3rd | 500 × 2² = 2,000 → capped at 1,500 ms |
| 4th | 500 × 2³ = 4,000 → capped at 1,500 ms |
| 5th | none: the 5th failure is the Result |
Only a function can be retried, since a promise has already started: safe(promise, policy) is
a type error. An invalid policy (only reachable from untyped code) throws at once, before the
call runs, as it is a bug in the caller rather than a failure of the call.
Durations are a number of milliseconds or a number with its unit and no space: ms, s, m,
h, d. "500ms" → 500, "2s" → 2,000, "1.5m" → 1.5 × 60,000 = 90,000, 2000 → 2,000. The
type rejects "soon" or "2" at compile time.
createSafe makes a safe whose errors are a type of your own, from a function that turns
whatever was thrown into one:
import { createSafe } from "xerror-js";
class HttpError extends Error {
constructor(
readonly status: number,
options?: ErrorOptions,
) {
super(`HTTP ${status}`, options);
}
}
const safeHttp = createSafe((thrown) =>
thrown instanceof HttpError ? thrown : new HttpError(500, { cause: thrown }),
);
const user = await safeHttp(fetchUser(id)); // Result<User, HttpError>
if (user.isErr() && user.err().status === 404) return notFound();The converter runs once per failure, retries included, and is given anything, an HttpError
already included. It must not throw: what it throws escapes safe.
| Export | Kind | What it is |
|---|---|---|
safe |
function | Wraps a promise or function into a Result, optionally retrying |
createSafe(convert) |
function | Makes a safe whose errors are the type convert returns |
Result<T, E> |
type | A value T or an error E; results come from safe, never new |
Ok, Err |
type | A Result known to have succeeded or failed |
SafePromise<T, E> |
type | A promise of a Result that never rejects, with Result's methods, awaited in one step |
Safe<E> |
type | The type of a safe whose errors are E |
SafeOf<R, E> |
type | What safe returns for a function returning R |
Convert<E> |
type | (thrown: unknown) => E, what createSafe takes |
RetryPolicy |
type | A retry policy written in full |
RetryPolicyShorthand |
type | A retry policy as "3x/500ms/2/5s" |
Duration, DurationText |
type | "500ms", "1.5m", or a number of milliseconds |
When a function's return type doesn't say whether it is a promise (unknown, or a generic T),
safe returns Result | SafePromise; await it and you get a Result either way.
- Rust's names.
isErr,ok,err,unwrap,expect,unwrapOr…: Rust'sResultmethods, in camelCase, so they read the same to anyone who knows Rust. - Methods, not a tagged union.
result.isErr()narrows like a discriminant, andunwrap()reads well at a boundary where a failure should just propagate. - One way in. No
fromPromise,fromThrowableortryAsync:safepicks by what it's given. - Rust's
Result, and no further.mapand the rest chain, on aSafePromisetoo:await safe(fetchUser(id)).map((user) => user.name).unwrapOr("guest"). Past that (pipelines, dependency injection, an effect system) reach for Effect. - The retry policy follows Temporal's field names, so it reads the same across a stack that uses both.
- Every failure is retried. There is no predicate to retry only some errors yet, nor jitter or cancellation.
pnpm install
pnpm typecheck # tsc over src/ and test/
pnpm test # vitest; fails below 100% coverage
pnpm lint # biome
pnpm build # dist/The conventions the code follows are in AGENTS.md.
MIT © Ahmed Ghait