oktry
v0.0.6
Published
Simple and ergonomic result type for TypeScript.
Downloads
31
Readme
OkTry
Why another result type library for TypeScript?
There are already many mature result type libraries to choose from. Just to name a few:
- NeverThrow
- fp-ts
- Effect
- t3dotgg/try-catch.ts (⭐ personal favorite!)
After using each of these I always find myself wanting something else. My ideal result type library has:
- The simplicity of
try-catch.ts - The composability of
fp-ts - The excellent DX of Rust's Result type
oktry is my attempt to meet that criteria.
Features
- Tiny footprint (288 lines of TypeScript)
- Does not try and replace
Promisewith a custom thenable - Simple primitives for chaining and composing calls
tryCatch/tryCatchSyncutilities- Pretty printed stack trace with chained context
- Easily eject original "native error"
Basic Example
// `Async<void>` is just `Promise<Result<void>>`.
async function level0(): Async<void> {
return Err(Error('level0'))
.attach('test', 'foo'); // Attach context to your errors!
}
async function level1(): Async<number> {
return level0()
.then(mapChain(Error('level1'))) // Create error chains!
.then(mapOk(_ => 42)); // Compose with `.then()`!
}
async function level2(): Async<string> {
// Returns a simple `Promise<Result<T, E>>`.
// No custom thenable that breaks `await`!
const result = await level1();
// Chainable methods!
return result
.chain(Error('level2'))
.attach({ bar: 1, baz: 'additional info' })
.map(x => x.toString());
}
async function test() {
let logNative = false
try {
await level2().then(unwrap);
} catch (error) {
if (error instanceof UnwrapError) {
console.error(error.toString());
if (logNative) {
// Optionally get the original "native error" for logging/observability.
console.error(error.toNativeError());
}
} else {
console.error(error);
}
}
}
test();Renders the innermost stacktrace first, automatically omits node internals, and nests the chained context:
Error: level0
at level0 (file:///home/nate/code/oktry/src/index.ts:293:14)
at level1 (file:///home/nate/code/oktry/src/index.ts:297:10)
at level2 (file:///home/nate/code/oktry/src/index.ts:303:24)
at test (file:///home/nate/code/oktry/src/index.ts:313:11)
at file:///home/nate/code/oktry/src/index.ts:324:1
Context chain (outermost first):
• UnwrapError: result unwrapped
at async test (file:///home/nate/code/oktry/src/index.ts:313:5)
• level2
at level2 (file:///home/nate/code/oktry/src/index.ts:306:12)
{
"bar": 1,
"baz": "additional info"
}
• level1
at level1 (file:///home/nate/code/oktry/src/index.ts:298:20)
• level0
at level0 (file:///home/nate/code/oktry/src/index.ts:293:14)
{
"test": "foo"
}tryAll()
Promise.all() is the default tool people generally reach for to resolve a bunch of promises concurrently. The issue is that Promise.all() actually has very counter-intuitive error handling.
The MDN page for Promise.all() says this:
The Promise.all() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason.
Notice that Promise.all() rejects for the first input promise that rejects. This means that after Promise.all() has rejected, all the other unresolved promises are still running! If they also reject those errors are swallowed.
For this reason, it's generally safer to use Promise.allSettled(), because it waits until all input promises either resolve or reject, which is almost always the correct behavior.
The trade-off is that Promise.allSettled() is a bit cumbersome to use. Even more so with a result type.
This is why oktry provides its own array-of-promises utility: tryAll().
You can use it like this:
// Use it the same as you would `Promise.all()` or `Promise.settled()`.
// It returns a _single_ `Result` value.
const results = await tryAll([
promise1,
promise2,
promise3,
]);
// `tryAll()` returns an error if one-or-more promise returns an error _or rejects_.
if (results.error) {
// Returns an aggregate error value `TryAllError`.
// `results.settled` is the settled array of results.
return results.chain(Error('Failed to resolve'))
}
// When successful, the result is an array of resolved values.
const [a, b, c] = results.ok;