Skip to content

Commit 58f208d

Browse files
fix: After an API error, all subsequent calls fail with the same error (#420)
* fix: After an API error, all subsequent calls fail with the same error * Format * Refactored error handling in _sendPromise, replacing try/catch with .catch() to simplify the code. * refactor: Move error handling inside promise chain * test: Ensure generateContent errors do not persist across calls
1 parent b4a10a5 commit 58f208d

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/methods/chat-session.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,27 @@ describe("ChatSession", () => {
4646
match.any,
4747
);
4848
});
49+
it("generateContent errors should not persist", async () => {
50+
const generateContentStub = stub(
51+
generateContentMethods,
52+
"generateContent",
53+
).rejects("generateContent failed");
54+
const chatSession = new ChatSession("MY_API_KEY", "a-model");
55+
await expect(chatSession.sendMessage("hello")).to.be.rejected;
56+
expect(generateContentStub).to.be.calledWith(
57+
"MY_API_KEY",
58+
"a-model",
59+
match.any,
60+
);
61+
restore();
62+
63+
// Subsequent call should succeed.
64+
const mockResponse = getMockResponse(
65+
"unary-success-basic-reply-short.json",
66+
);
67+
stub(request, "makeModelRequest").resolves(mockResponse as Response);
68+
await expect(chatSession.sendMessage("hello")).to.not.be.rejected;
69+
});
4970
});
5071
describe("sendMessageRecitationErrorNotAddingResponseToHistory()", () => {
5172
it("generateContent errors should be catchable", async () => {

src/methods/chat-session.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,11 @@ export class ChatSession {
126126
}
127127
}
128128
finalResult = result;
129+
})
130+
.catch((e) => {
131+
// Resets _sendPromise to avoid subsequent calls failing and throw error.
132+
this._sendPromise = Promise.resolve();
133+
throw e;
129134
});
130135
await this._sendPromise;
131136
return finalResult;

0 commit comments

Comments
 (0)