From 7ec24d632e6f0ffc978d1c9404c57a47b4236f3d Mon Sep 17 00:00:00 2001 From: Ahmed Abushagur Date: Mon, 23 Mar 2026 16:41:28 -0700 Subject: [PATCH] fix: rethrow normalized Error in tryCatchIf/asyncTryCatchIf MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the guard returns false, both functions re-threw the raw caught value (e) instead of the normalized Error (err). If a non-Error value was thrown (string, number), downstream handlers received inconsistent types instead of always getting Error instances. Changed throw e → throw err in both functions. Co-Authored-By: Claude Opus 4.6 (1M context) --- packages/shared/src/__tests__/result.test.ts | 29 ++++++++++++++++++++ packages/shared/src/result.ts | 4 +-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/__tests__/result.test.ts b/packages/shared/src/__tests__/result.test.ts index 7e56a82c7..67f2da6a4 100644 --- a/packages/shared/src/__tests__/result.test.ts +++ b/packages/shared/src/__tests__/result.test.ts @@ -134,6 +134,21 @@ describe("tryCatchIf", () => { }), ).toThrow("unexpected"); }); + + it("re-throws non-Error values as normalized Error instances", () => { + const guard = () => false; + // Wrap in tryCatch to capture the re-thrown value without raw try/catch + const result = tryCatch(() => + tryCatchIf(guard, () => { + throw "raw string error"; + }), + ); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toBeInstanceOf(Error); + expect(result.error.message).toBe("raw string error"); + } + }); }); describe("asyncTryCatchIf", () => { @@ -167,6 +182,20 @@ describe("asyncTryCatchIf", () => { }), ).rejects.toThrow("unexpected"); }); + + it("re-throws non-Error values as normalized Error instances", async () => { + const guard = () => false; + const result = await asyncTryCatch(() => + asyncTryCatchIf(guard, async () => { + throw 404; + }), + ); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toBeInstanceOf(Error); + expect(result.error.message).toBe("404"); + } + }); }); describe("unwrapOr", () => { diff --git a/packages/shared/src/result.ts b/packages/shared/src/result.ts index 326175311..2d25b5873 100644 --- a/packages/shared/src/result.ts +++ b/packages/shared/src/result.ts @@ -54,7 +54,7 @@ export function tryCatchIf(guard: (err: Error) => boolean, fn: () => T): Resu if (guard(err)) { return Err(err); } - throw e; + throw err; } } @@ -70,7 +70,7 @@ export async function asyncTryCatchIf(guard: (err: Error) => boolean, fn: () if (guard(err)) { return Err(err); } - throw e; + throw err; } }