Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/core/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ export class APIError<
return new APIConnectionError({ message, cause: castToError(errorResponse) });
}

const error = (errorResponse as Record<string, any>)?.['error'];
const data = errorResponse as Record<string, any> | undefined;
const error = data?.['error'] ?? data;

if (status === 400) {
return new BadRequestError(status, error, message, headers);
Expand Down
30 changes: 29 additions & 1 deletion tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { APIPromise } from 'openai/core/api-promise';

import util from 'node:util';
import OpenAI from 'openai';
import { APIUserAbortError } from 'openai';
import { APIUserAbortError, UnprocessableEntityError } from 'openai';
const defaultFetch = fetch;

describe('instantiate client', () => {
Expand Down Expand Up @@ -241,6 +241,34 @@ describe('instantiate client', () => {
expect(response).toEqual({ url: 'http://localhost:5000/foo', custom: true });
});

test('error message falls back to the whole response body when error field is absent', async () => {
const errorBody = { detail: '422: The model gpt-5-gibberish does not exist.' };
const client = new OpenAI({
baseURL: 'http://localhost:5000/',
apiKey: 'My API Key',
fetch: () => {
return Promise.resolve(
new Response(JSON.stringify(errorBody), {
status: 422,
headers: { 'Content-Type': 'application/json' },
}),
);
},
});

try {
await client.get('/foo');
throw new Error('Expected request to fail');
} catch (error) {
expect(error).toBeInstanceOf(UnprocessableEntityError);
expect(error).toMatchObject({
status: 422,
error: errorBody,
message: `422 ${JSON.stringify(errorBody)}`,
});
}
});

test('explicit global fetch', async () => {
// make sure the global fetch type is assignable to our Fetch type
const client = new OpenAI({
Expand Down