$trap
Trap allows us to wrap risky code and return a result, allowing us to seamlessly trap exceptions at their source.
ts
const res = await $trap(async () => {
const riskyOutput = await someRiskyCode()
return ok(riskyOutput, $code.ok)
})If this code throws, the exception will be caught and returned as an err().
$trap(fn)
Handles both sync and async functions that return a Result<T, E>. If the function throws, it catches the error and returns an err(..., $code.unknown).
ts
$trap(() => Result<T, E>) → Promise<Result<T, E>>
$trap(async () => Result<T, E>) → Promise<Result<T, E>>Example with async work inside:
ts
const res = await $trap(async () => {
const data = await load()
return ok(data, $code.ok)
})ts
const result = await $trap(() => mightThrowButReturnsResult())$trapBag(fn)
Same as $trap, but returns a $result(...) wrapper bag instead of a plain Result. Just a shorthand.
ts
$trapBag(() => Result<T, E>) → ReturnBag<T, E>✅ Use this if you want .map(), .unwrap(), .tapOk() etc. directly on the result.
Example
ts
const res = $trapBag(() => {
// ...risky logic
return ok(null, $code.ok)
})
// Comes with result methods
res.isOk
res.mapErr((e) => console.log(e))