From 6e9f92625d5974a507f5922fdab97f0f80bd0263 Mon Sep 17 00:00:00 2001 From: Chris Wilkinson Date: Mon, 11 Mar 2024 12:08:32 +0000 Subject: [PATCH] Don't fail when a value can't be converted to a primitive --- src/Either.ts | 6 +++++- test/Either.ts | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/Either.ts b/src/Either.ts index 3c98906af..57fe3d1e0 100644 --- a/src/Either.ts +++ b/src/Either.ts @@ -1456,7 +1456,11 @@ export const toUnion: (fa: Either) => E | A = /*#__PURE__*/ foldW(id * @since 2.0.0 */ export function toError(e: unknown): Error { - return e instanceof Error ? e : new Error(String(e)) + try { + return e instanceof Error ? e : new Error(String(e)) + } catch (error) { + return new Error() + } } /** diff --git a/test/Either.ts b/test/Either.ts index 93b626838..aed8e60f1 100644 --- a/test/Either.ts +++ b/test/Either.ts @@ -393,6 +393,20 @@ describe.concurrent('Either', () => { }, _.toError), _.left(new Error('string error')) ) + + U.deepStrictEqual( + _.tryCatch(() => { + throw Object.create(null) + }, _.toError), + _.left(new Error()) + ) + + U.deepStrictEqual( + _.tryCatch(() => { + throw { toString: [] } + }, _.toError), + _.left(new Error()) + ) }) describe.concurrent('getEq', () => {