getbrevo / brevo-php

A fully-featured PHP API client to interact with Brevo.
https://developers.brevo.com/
MIT License
49 stars 22 forks source link

Fatal error with Guzzle ClientException #13

Open Colir opened 1 year ago

Colir commented 1 year ago

Hi. I've just installed the Brevo sdk. All work great, but when the API v3 returns a bad request, this triggers a fatal error by Guzzle

here is my log example

PHP Fatal error:  Uncaught GuzzleHttp\Exception\ClientException: Client error: `POST https://api.brevo.com/v3/contacts` resulted in a `400 Bad Request` response:
{"code":"duplicate_parameter","message":"Unable to update contact, SMS or WHATSAPP are already associated with another C (truncated...)

and here is my code

 $response = $this->client->request('POST', 'https://api.brevo.com/v3/contacts', [ 
            'body' => json_encode($contact),
            'headers' => [
                'accept' => 'application/json',
                'api-key' => BREVO_API_KEY,
                'content-type' => 'application/json',
            ],
        ]);

 try {
    $statusCode = $response->getStatusCode();
    $responseBody = $response->getBody();
    $responseArray = json_decode($responseBody,true);

    if( $statusCode == 201){
        return array('success' => true, 'message' =>  $responseArray);
    } else {
        return array('success' => false, 'message' => $responseArray['message']);
    }

 } catch (ClientException $e) {
            write_log('client exception');
            write_log($e->getMessage());

}catch (RequestException $e) {
            write_log('request exception');
            write_log($e->getMessage());  

} catch (Exception $e) {
    write_log($e->getMessage());
}

Does anyone can help me to catch this error ?

thank you

Colir commented 1 year ago

Here is the solution: As the exception occurs on the Client, the first try{} must wrap the $response variable

try{ $response = $this->client->request(....) } catch ( Exception $e ){ .... }