8000 error handling: error message is sometimes empty - fixes https://gith… · openai-php/client@c4ae556 · GitHub
[go: up one dir, main page]

Skip to content

Commit c4ae556

Browse files
committed
error handling: error message is sometimes empty - fixes openai-php/laravel#47
1 parent a56748d commit c4ae556

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

src/Exceptions/ErrorException.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ final class ErrorException extends Exception
1515
*/
1616
public function __construct(private readonly array $contents)
1717
{
18-
$message = $contents['message'];
18+
$message = ($contents['message'] ?: $this->contents['code']) ?: 'Unknown error';
1919

2020
if (is_array($message)) {
2121
$message = implode("\n", $message);

tests/Transporters/HttpTransporter.php

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,58 @@
215215
});
216216
});
217217

218+
test('error message may be empty', function () {
219+
$payload = Payload::create('completions', ['model' => 'gpt-4']);
220+
221+
$response = new Response(404, ['Content-Type' => 'application/json; charset=utf-8'], json_encode([
222+
'error' => [
223+
'message' => '',
224+
'type' => 'invalid_request_error',
225+
'param' => null,
226+
'code' => 'invalid_api_key',
227+
],
228+
]));
229+
230+
$this->client
231+
->shouldReceive('sendRequest')
232+
->once()
233+
->andReturn($response);
234+
235+
expect(fn () => $this->http->requestObject($payload))
236+
->toThrow(function (ErrorException $e) {
237+
expect($e->getMessage())->toBe('invalid_api_key')
238+
->and($e->getErrorMessage())->toBe('invalid_api_key')
239+
->and($e->getErrorCode())->toBe('invalid_api_key')
240+
->and($e->getErrorType())->toBe('invalid_request_error');
241+
});
242+
});
243+
244+
test('error message and code may be empty', function () {
245+
$payload = Payload::create('completions', ['model' => 'gpt-4']);
246+
247+
$response = new Response(404, ['Content-Type' => 'application/json; charset=utf-8'], json_encode([
248+
'error' => [
249+
'message' => '',
250+
'type' => 'invalid_request_error',
251+
'param' => null,
252+
'code' => null,
253+
],
254+
]));
255+
256+
$this->client
257+
->shouldReceive('sendRequest')
258+
->once()
259+
->andReturn($response);
260+
261+
expect(fn () => $this->http->requestObject($payload))
262+
->toThrow(function (ErrorException $e) {
263+
expect($e->getMessage())->toBe('Unknown error')
264+
->and($e->getErrorMessage())->toBe('Unknown error')
265+
->and($e->getErrorCode())->toBeNull()
266+
->and($e->getErrorType())->toBe('invalid_request_error');
267+
});
268+
});
269+
218270
test('request object client errors', function () {
219271
$payload = Payload::list('models');
220272

0 commit comments

Comments
 (0)
0