This repository has been archived by the owner on Dec 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tryify.ts
57 lines (54 loc) 路 1.94 KB
/
tryify.ts
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// deno-lint-ignore no-explicit-any
type params = any[];
type func<P extends params, R> = (...args: P) => R;
type asyncFunc<P extends params, R> = func<P, PromiseLike<R>>;
/**
* The result of an attempted method.
*/
export type Tried<T> = [Error, undefined] | [undefined, T];
/**
* wraps a function and returns a version that will return errors instead of throwing them
* @param {(args: any) => any} func the function that will be wrapped
* @example ```ts
* const errorFunc = (arg1: string, arg2: number): string => {throw Error('oops!')}
* const tryFunc = tryify(errorFunc);
* const [error, result] = tryFunc('hello world', 100) // or
* const [error, result] = tryify(errorFunc)('hello world', 200)
* // error.message = 'oops!' and result is undefined
* ```
*/
// deno-lint-ignore no-explicit-any
export function tryify<P extends any[], R>(
func: func<P, R> extends asyncFunc<P, R> ? never : func<P, R>,
): (...args: Parameters<typeof func>) => Tried<R> {
return (...args) => {
try {
return [undefined, func(...args)];
} catch (error) {
return [error, undefined];
}
};
}
/**
* wraps an async function and returns a version that will return errors instead of throwing them
* @param {(args: any) => Promise<any>} func the function that will be wrapped
* @example ```ts
* const errorFunc = async (arg1: string, arg2: number): string => Promise.reject('Whoops!')
* const tryFunc = tryify(errorFunc);
* const [error, result] = await tryFunc('hello world', 100) // or
* const [error, result] = await tryify(errorFunc)('hello world', 200)
* // error.message = 'Whoops!' and result is undefined
* ```
*/
// deno-lint-ignore no-explicit-any
export function tryifyAsync<P extends any[], R>(
func: asyncFunc<P, R>,
): (...args: Parameters<typeof func>) => PromiseLike<Tried<R>> {
return async (...args) => {
try {
return [undefined, await func(...args)];
} catch (error) {
return [error, undefined];
}
};
}