summaryrefslogtreecommitdiff
path: root/src/utils/error.ts
blob: 40f0fc07fc8bc894b76260d3e52cb5620f71b503 (plain)
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
/**
 * Tries to call {@linkcode fn} throwing an exception with the {@linkcode message}
 * if an error occurs
 *
 * @example
 * // Before
 * let value;
 * try {
 *   value = someMethod();
 * } catch(e) {
 *   throw new Error('My specific message', { cause: e })
 * }
 *
 * // After
 * const value = mapError(
 *   () => someMethod(),
 *   'My specific message'
 * );
 */
export function mapException<T>(fn: () => T, message: string): T {
    try {
        return fn();
    } catch (e) {
        throw new Error(message, {
            cause: e,
        });
    }
}