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', () => {