Eric Bower
·
26 Aug 24
safe.ts
1import type { Callable, Operation, Result } from "../deps.ts";
2import { call, Err, Ok } from "../deps.ts";
3
4/**
5 * The goal of `safe` is to wrap Operations to prevent them from raising
6 * and error. The result of `safe` is always a {@link Result} type.
7 *
8 * @example
9 * ```ts
10 * import { safe } from "starfx";
11 *
12 * function* run() {
13 * const results = yield* safe(fetch("api.com"));
14 * if (result.ok) {
15 * console.log(result.value);
16 * } else {
17 * console.error(result.error);
18 * }
19 * }
20 * ```
21 */
22export function* safe<T>(operator: Callable<T>): Operation<Result<T>> {
23 try {
24 const value = yield* call<T>(operator as any);
25 return Ok(value);
26 } catch (error) {
27 return Err(error);
28 }
29}