-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
167 lines (156 loc) · 3.92 KB
/
mod.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// deno-lint-ignore-file no-explicit-any
const baseErrorSymbol = Symbol("Error");
declare global {
interface Error {
[baseErrorSymbol]: true;
}
}
/**
* A custom class that extends Error that allows for namable Errors inside
* the type system.
*
* ```
* const myError = new Err("MyError");
* // myError: Err<"MyError">
* ```
*/
export class Err<N extends string = "Error"> extends Error {
name!: N;
cause?: Err;
constructor(name?: N, message?: string, cause?: Error) {
super(message, {
cause,
});
if (name) {
this.name = name;
}
}
}
/**
* A union type between a return type `T` and an Error type `E`.
*/
export type Result<T, E extends Error | Err = Err<string>> = T | E;
type ExtractName<T> = T extends Error & { name: infer N } ? N : never;
type SymboledError<N extends string> = { [baseErrorSymbol]: true; name: N };
/**
* Returns whether a `Result` is an instance of an Error. If a `name` is provided,
* checks if the Error's name or it's causes contain an Error with that name.
*
* ```
* const result = await CaptureErr("Fetch Error", async (): MyStruct => {
* const res = await fetch(url);
* return await res.json();
* });
* if(isErr(result, "Fetch Error")) {
* // result: Err<"Fetch Error">
* } else {
* // result: MyStruct
* }
* ```
*/
export function isErr<
R extends Result<any>,
N extends ExtractName<R> & string,
>(
result: R,
name?: N,
): result is Extract<R, SymboledError<N>> {
if (!(result instanceof Error)) return false;
if (name === undefined) return true;
if (result.name === name) return true;
if (result.cause instanceof Error) {
return isErr(result.cause, name);
}
return false;
}
/**
* Returns the result if it's not an Error, otherwise returns `null`.
*
* The primary use of this function is with the nullish coalescence operator
* `??` in providing a value if the result ended up being an Error.
*
* ```
* function parseJSON(input: string) {
* const json = CaptureErr("JSON Parse Error",
* () => JSON.parse(input)
* )
* return Ok(json) ?? {}
* }
* ```
*/
export function Ok<
R extends any,
>(
result: Result<R>,
): R | null {
if (isErr(result)) {
return null;
}
return result;
}
type InnerType<T> = T extends Promise<infer U> ? U : never;
/**
* Captures an Error in the given `callback` function and returns it as a
* `Result` with the specified Error `name`.
*
* ```
* // result: MyStruct | Err<"Fetch Error">
* const result = await CaptureErr("Fetch Error", async (): MyStruct => {
* const res = await fetch(url);
* return await res.json();
* });
* ```
*/
export function CaptureErr<
F extends (...args: any[]) => any,
N extends string,
R extends ReturnType<F>,
>(
name: N,
callback: F,
message?: string,
): R extends Promise<any> ? Promise<InnerType<R> | Err<N>> : R | Err<N> {
try {
const result = callback();
if (result instanceof Promise) {
return result.catch((capturedError: Error) => {
capturedError.cause = new Err(
name,
message,
);
return capturedError as Err<N>;
}) as any;
// ^ BEGONE TYPE ERRORS!
// TODO(ybabts) figure out how to get this conditional type to work
}
return result;
} catch (capturedError) {
capturedError.cause = new Err(
name,
message,
);
return capturedError;
}
}
/**
* Unwraps a `Result`, throwing the Error if one exists.
*
* This should only be used
* when the given Error cannot be resolved gracefully or you are completely
* sure the `Result` will not produce an Error.
* ```
* const result = await CaptureErr("Fetch Error", async (): MyStruct => {
* const res = await fetch(url);
* return await res.json();
* });
* // ^ result: MyStruct | Err<"Fetch Error"
* const json = UnwrapErr(result);
* // ^ json: MyStruct
* ```
*/
export function UnwrapErr<T>(result: Result<T>): T {
if (result instanceof Error) {
throw result;
}
return result;
}