@sanely/try
v0.1.0
Published
A better try/catch for TypeScript
Maintainers
Readme
@sanely/try is a small execution layer for TypeScript. You write normal functions. The package runs them, applies your retry, timeout, and cancellation policy, and returns errors as typed values instead of thrown exceptions.
The return type tells you everything that can come back: your value, the failures that you map, and the policy failures that your chain can add.
import * as try$ from "@sanely/try"
class OrderLookupError extends Error {}
const result = await try$
.retry(3) // Up to 3 attempts in total, including the first
.timeout("5s") // One total deadline across all attempts, in milliseconds or a time expression
.run({
try: async ({ signal }) => {
const response = await fetch("https://api.example.com/orders/ord_123", {
signal, // Aborts when the deadline expires
})
if (!response.ok) {
throw new Error(`unexpected status ${response.status}`)
}
const order = (await response.json()) as { status: "pending" | "shipped" }
return order.status
},
catch: () => new OrderLookupError("could not load the order"),
})
// result is "pending" | "shipped" | OrderLookupError | TimeoutErrorFeatures
- Errors as values. Thrown errors come back as part of the return type.
- Execution policies. Add retries, one total deadline, and cancellation without a change to the work.
- Sync and async parity.
runSync(...)maps failures and builds result unions the same way asrun(...). Policies that wait or interrupt are async only. - Named task orchestration. Run concurrent and ordered workflows as objects of named tasks.
- Instrumentation hooks. Observe execution with
wrap(...)for logs, traces, and metrics. - Resource cleanup. Register cleanup that runs when a scope or an orchestration ends, with
disposer()andthis.$disposer. - No external dependencies. The only runtime dependency is
@sanely/duration, which reads time expressions such as"500ms".
Install
npm install @sanely/tryThe package needs AbortSignal.any and Promise.withResolvers. Node.js 22 or later has both, and the package declares that floor in its engines field. Recent Bun, Deno, and current browsers also have both.
Get started
Run a function. A thrown error comes back as an UnhandledException value:
import * as try$ from "@sanely/try"
const result = await try$.run(async () => {
const response = await fetch("https://api.example.com/health")
return response.status
})
// result is number | UnhandledExceptionUse the object form to map thrown errors to your own error types:
class InvalidConfigError extends Error {}
const config = try$.runSync({
try: () => JSON.parse(process.env.APP_CONFIG ?? "") as { port: number },
catch: () => new InvalidConfigError("APP_CONFIG is not valid JSON"),
})
// config is { port: number } | InvalidConfigErrorDocumentation
How-to guides:
- How to map thrown errors to domain errors
- How to add retries, a deadline, and cancellation
- How to log and trace execution with
wrap - How to run tasks in parallel
- How to run an ordered workflow with
flow - How to compose results with
gen - How to clean up resources with
disposer
Reference:
Explanation:
Contributing
Read the contributor guide before changing the package.
Acknowledgments
better-resultfor typed result-oriented error handling in TypeScript.effectfor structured, composable models of execution, failure, and concurrency.better-allfor task orchestration patterns over object-shaped work graphs.errorefor modeling errors as unions instead of tuples.
Made with 🥐 pastry.
License
MIT. See LICENSE.
