diff --git a/src/Transporters/HttpTransporter.php b/src/Transporters/HttpTransporter.php index 0b1d8af6..880a85df 100644 --- a/src/Transporters/HttpTransporter.php +++ b/src/Transporters/HttpTransporter.php @@ -172,11 +172,16 @@ private function throwIfJsonError(ResponseInterface $response, string|ResponseIn } try { - /** @var array{error?: string|array{message: string|array, type: string, code: string}} $data */ + /** @var (array{error?: string|array{message: string|array, type: string, code: string}})|(array{0?: array{error?: string|array{message: string|array, code: string, status: string, type?: string}}}) $data */ $data = json_decode($contents, true, flags: JSON_THROW_ON_ERROR); if (isset($data['error'])) { throw new ErrorException($data['error'], $response); + } elseif (isset($data[0]['error'])) { + if (! isset($data[0]['error']['type']) && isset($data[0]['error']['status'])) { + $data[0]['error']['type'] = $data[0]['error']['status']; + } + throw new ErrorException($data[0]['error'], $response); } } catch (JsonException $jsonException) { throw new UnserializableResponse($jsonException, $response); diff --git a/tests/Transporters/HttpTransporter.php b/tests/Transporters/HttpTransporter.php index 813b9e0e..eed44907 100644 --- a/tests/Transporters/HttpTransporter.php +++ b/tests/Transporters/HttpTransporter.php @@ -624,3 +624,53 @@ $this->http->requestObject($payload); }); + +test('error for gemini with invalid parameter', function (string $requestMethod) { + $payload = Payload::create('completions', [ + 'model' => 'gemini-2.5-flash', + 'messages' => [ + [ + 'role' => 'system', + 'content' => 'You can use tools if needed.', + ], + [ + 'role' => 'user', + 'content' => 'Yo', + ], + ], + 'ddd' => 'auto', + ]); + + $response = new Response(400, ['Content-Type' => 'application/json; charset=utf-8'], json_encode( + [[ + 'error' => [ + 'code' => 400, + 'message' => 'Invalid JSON payload received. Unknown name "ddd": Cannot find field.', + 'status' => 'INVALID_ARGUMENT', + 'details' => [ + [ + '@type' => 'type.googleapis.com/google.rpc.BadRequest', + 'fieldViolations' => [ + [ + 'description' => 'Invalid JSON payload received. Unknown name "ddd": Cannot find field.', + ], + ], + ], + ], + ], + ]] + )); + + $this->client + ->shouldReceive('sendRequest') + ->once() + ->andReturn($response); + + expect(fn () => $this->http->$requestMethod($payload)) + ->toThrow(function (ErrorException $e) { + expect($e->getMessage())->toBe('Invalid JSON payload received. Unknown name "ddd": Cannot find field.') + ->and($e->getErrorMessage())->toBe('Invalid JSON payload received. Unknown name "ddd": Cannot find field.') + ->and($e->getErrorCode())->toBe(400) + ->and($e->getErrorType())->toBe('INVALID_ARGUMENT'); + }); +})->with('request methods');