fix(ai-client): improve error handling in chat function

- Add explicit check for empty choices array
- Add optional chaining for message property access
- Throw descriptive error when API returns no content
- Fixes debugging issues when upstream returns empty responses

Resolves: chat.ts silent empty string return on malformed responses
This commit is contained in:
yuanzonghao
2026-05-31 12:38:55 +08:00
parent def1b25bd9
commit c610efcb26
+10 -1
View File
@@ -38,5 +38,14 @@ export async function chat(
const json = (await res.json()) as {
choices: { message: { content: string } }[];
};
return json.choices[0]?.message.content ?? "";
// 修复问题2和问题5:检查choices是否为空,以及message是否存在
const content = json.choices?.[0]?.message?.content;
if (content === undefined || content === null) {
throw new Error(
`Chat API returned no content. Response: ${JSON.stringify(json).slice(0, 500)}`
);
}
return content;
}