openai-php / client

⚡️ OpenAI PHP is a supercharged community-maintained PHP API client that allows you to interact with OpenAI API.
MIT License
4.75k stars 491 forks source link

Error Handling #124

Closed Noou-Ben closed 1 year ago

Noou-Ben commented 1 year ago

Apologies in advance if I am being stupid here!

If an incorrect API key is provided then the HttpTransport throws an exception with the response error. This results in a 500 error. Is there a way to avoid the 500 error and just output the response error to the end user?

pb30 commented 1 year ago

Wrap the call in a try catch and handle the exception however you'd like

Noou-Ben commented 1 year ago

@pb30 ah yes, thank you. This does work however I get the full error, I just want the message from OpenAI, any suggestions?

OpenAI\Exceptions\ErrorException: The model:gpt-4does not exist in H:\[..]\openai-php\client\src\Transporters\HttpTransporter.php:130 Stack trace: #0 H:\[..]\openai-php\client\src\Transporters\HttpTransporter.php(55): OpenAI\Transporters\HttpTransporter->throwIfJsonError(Array, '{\n "error": ...') #1 H:\[..]\openai-php\client\src\Resources\Chat.php(32): OpenAI\Transporters\HttpTransporter->requestObject(Object(OpenAI\ValueObjects\Transporter\Payload))

pb30 commented 1 year ago
try {
....
} catch (\OpenAI\Exceptions\ErrorException $e) {
    $type = $e->getErrorType(); // "invalid_request_error"
    $errorCode = $e->getErrorCode(); // "invalid_api_key"
    ...
}
Noou-Ben commented 1 year ago

You gent @pb30. Thank you!