Improve OpenAI provider error handling and add tests

This commit is contained in:
vgcman16 2025-06-05 21:34:37 -05:00
parent 1d66831395
commit 947d729fd9
3 changed files with 51 additions and 2 deletions

View File

@ -0,0 +1,35 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
vi.mock('../manager', () => ({
LLMManager: class {
static getInstance() {
return { env: {} };
}
},
}));
import OpenAIProvider from './openai';
const provider = new OpenAIProvider();
describe('OpenAIProvider.getDynamicModels', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('throws error when fetch fails', async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ error: { message: 'Invalid API key' } }), {
status: 401,
statusText: 'Unauthorized',
}),
);
vi.stubGlobal('fetch', fetchMock);
vi.spyOn(provider as any, 'getProviderBaseUrlAndKey').mockReturnValue({
apiKey: 'bad-key',
});
await expect(provider.getDynamicModels()).rejects.toThrow('Failed to fetch models from OpenAI: Invalid API key');
});
});

View File

@ -43,7 +43,19 @@ export default class OpenAIProvider extends BaseProvider {
},
});
const res = (await response.json()) as any;
let res: any;
try {
res = await response.json();
} catch (error) {
throw new Error(`Failed to parse response from ${this.name}: ${(error as Error).message}`);
}
if (!response.ok) {
const message = res?.error?.message || response.statusText;
throw new Error(`Failed to fetch models from ${this.name}: ${message}`);
}
const staticModelIds = this.staticModels.map((m) => m.name);
const data = res.data.filter(

View File

@ -128,7 +128,9 @@ export default defineConfig((config) => {
},
}),
UnoCSS(),
tsconfigPaths(),
tsconfigPaths({
ignoreConfigErrors: true,
}),
chrome129IssuePlugin(),
config.mode === 'production' && optimizeCssModules({ apply: 'build' }),
],