From bce557cc2dc767628bed6aac87301a1be7c5431b Mon Sep 17 00:00:00 2001 From: rxliuli Date: Tue, 4 Nov 2025 05:03:50 +0800 Subject: init commit --- src/utils/error.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/utils/error.ts (limited to 'src/utils/error.ts') diff --git a/src/utils/error.ts b/src/utils/error.ts new file mode 100644 index 0000000..40f0fc0 --- /dev/null +++ b/src/utils/error.ts @@ -0,0 +1,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(fn: () => T, message: string): T { + try { + return fn(); + } catch (e) { + throw new Error(message, { + cause: e, + }); + } +} -- cgit v1.2.3