-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathalter.ts
More file actions
24 lines (24 loc) · 612 Bytes
/
alter.ts
File metadata and controls
24 lines (24 loc) · 612 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
/**
* Alter the error of a function if an error is thrown.
*
* @param fn - The function to execute.
* @param alt - The value to throw if an error is thrown.
* @returns The result of the function.
* @throws The value of alt.
* @example
*
* ```ts
* import { assertThrows } from "@std/assert";
* import { alter } from "@core/errorutil/alter";
*
* console.log(alter(() => 1, "err2")); // 1
* assertThrows(() => alter(() => { throw "err1" }, "err2"), "err2"); // "err2" is thrown
* ```
*/
export function alter<T, E>(fn: () => T, alt: E): T {
try {
return fn();
} catch {
throw alt;
}
}