summaryrefslogtreecommitdiff
path: root/src/utils/error.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils/error.ts')
-rw-r--r--src/utils/error.ts28
1 files changed, 28 insertions, 0 deletions
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<T>(fn: () => T, message: string): T {
+ try {
+ return fn();
+ } catch (e) {
+ throw new Error(message, {
+ cause: e,
+ });
+ }
+}