-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsafe.ts
More file actions
35 lines (33 loc) · 914 Bytes
/
safe.ts
File metadata and controls
35 lines (33 loc) · 914 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import type { Operation, Result } from "npm:effection@4.0.0-alpha.8";
import { call, Err, Ok } from "npm:effection@4.0.0-alpha.8";
/**
* The goal of `safe` is to wrap Operations to prevent them from raising
* and error. The result of `safe` is always a {@link Result} type.
*
* @example
* ```ts
* import { safe } from "starfx";
*
* function* run() {
* const results = yield* safe(fetch("api.com"));
* if (result.ok) {
* console.log(result.value);
* } else {
* console.error(result.error);
* }
* }
* ```
*/
function isError(error: unknown): error is Error {
return error instanceof Error;
}
export function* safe<T, TArgs extends unknown[] = []>(
operator: (...args: TArgs) => Operation<T>,
): Operation<Result<T>> {
try {
const value = yield* call(operator);
return Ok(value);
} catch (error) {
return Err(isError(error) ? error : new Error(String(error)));
}
}