mirror of
https://github.com/lobehub/lobe-chat.git
synced 2026-06-14 03:30:19 +00:00
🐛 fix: preserve OpenRouter model error bodies
This commit is contained in:
@@ -1350,11 +1350,11 @@ describe('LobeOpenRouterAI - custom features', () => {
|
||||
it('should throw with cause when fetch fails', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
json: async () => ({ error: { message: 'Unauthorized' } }),
|
||||
ok: false,
|
||||
status: 401,
|
||||
}),
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: { message: 'Unauthorized' } }), { status: 401 }),
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -1370,6 +1370,25 @@ describe('LobeOpenRouterAI - custom features', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('should preserve non-JSON error body when model request fails', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(new Response('<html>bad gateway</html>', { status: 502 })),
|
||||
);
|
||||
|
||||
try {
|
||||
await params.models();
|
||||
expect.fail('Expected models() to reject');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
expect((error as Error).message).toBe('OpenRouter models API request failed');
|
||||
expect((error as Error).cause).toEqual({
|
||||
body: '<html>bad gateway</html>',
|
||||
status: 502,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('should preserve network errors', async () => {
|
||||
const error = new Error('Network error');
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(error));
|
||||
|
||||
@@ -10,6 +10,18 @@ const formatPrice = (price?: string) => {
|
||||
return Number((Number(price) * 1e6).toPrecision(5));
|
||||
};
|
||||
|
||||
const parseOpenRouterModelsErrorBody = async (response: Response) => {
|
||||
const body = await response.text();
|
||||
|
||||
if (!body) return '';
|
||||
|
||||
try {
|
||||
return JSON.parse(body) as unknown;
|
||||
} catch {
|
||||
return body;
|
||||
}
|
||||
};
|
||||
|
||||
export const params = {
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
chatCompletion: {
|
||||
@@ -94,14 +106,15 @@ export const params = {
|
||||
},
|
||||
models: async () => {
|
||||
const response = await fetch('https://openrouter.ai/api/v1/models');
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok === false) {
|
||||
const body = await parseOpenRouterModelsErrorBody(response);
|
||||
throw new Error('OpenRouter models API request failed', {
|
||||
cause: { body: data, status: response.status },
|
||||
cause: { body, status: response.status },
|
||||
});
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const modelList = data['data'];
|
||||
|
||||
if (!Array.isArray(modelList)) {
|
||||
|
||||
Reference in New Issue
Block a user