🐛 fix: preserve OpenRouter model error bodies

This commit is contained in:
yutengjing
2026-06-13 12:25:56 +08:00
parent 3a92bbd579
commit 3325b98c3a
2 changed files with 39 additions and 7 deletions
@@ -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)) {