diff --git a/packages/better-fetch/src/fetch.ts b/packages/better-fetch/src/fetch.ts index 1a8a61c..4cdbb80 100644 --- a/packages/better-fetch/src/fetch.ts +++ b/packages/better-fetch/src/fetch.ts @@ -155,7 +155,10 @@ export const betterFetch = async < } as any; } const parser = options?.jsonParser ?? jsonParse; - const responseText = await response.text(); + const responseToRead = options?.hookOptions?.cloneResponse + ? response.clone() + : response; + const responseText = await responseToRead.text(); const isJSONResponse = isJSONParsable(responseText); const errorObject = isJSONResponse ? await parser(responseText) : null; /** diff --git a/packages/better-fetch/src/test/fetch.test.ts b/packages/better-fetch/src/test/fetch.test.ts index 83a08da..c738f9a 100644 --- a/packages/better-fetch/src/test/fetch.test.ts +++ b/packages/better-fetch/src/test/fetch.test.ts @@ -396,6 +396,28 @@ describe("hooks", () => { expect(onSuccess).not.toHaveBeenCalled(); }); + it("should call onError with cloneResponse enabled", async () => { + const onError = vi.fn(); + const f = createFetch({ + baseURL: "http://localhost:4001", + customFetchImpl: async () => { + return new Response(JSON.stringify({ message: "Server Error" }), { + status: 500, + }); + }, + onError, + hookOptions: { cloneResponse: true }, + }); + + const result = await f("/test"); + + expect(onError).toHaveBeenCalled(); + expect(result.error).toMatchObject({ + status: 500, + message: "Server Error", + }); + }); + it("should work with relative url", async () => { const onRequest = vi.fn(); const onResponse = vi.fn();