x43
x43

Reputation: 316

Prevent Guzzle from creating a 500 error on non 200 response

On my website I use Guzzle to report hacking attempts to AbuseIPDB. For example, when a hacker visits /.env a report will automatically get filed. AbuseIPDB gives a 429 when you send more than one report for the same IP. Guzzle then gives a 500 error as AbuseIPDB did not give a 200 OK.

My question is, how can I prevent Guzzle from killing the program when it gets a non 200 OK response? Is it possible to do this?

Upvotes: 0

Views: 676

Answers (1)

bhucho
bhucho

Reputation: 3420

A GuzzleHttp\Exception\ServerException is thrown for 500 level errors if the http_errors request option is set to true. This exception extends from GuzzleHttp\Exception\BadResponseException.

I will add a sample example to how to handle only 500 errors,

try{
  $client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]);
  
  $guzzleResponse = $client->get('/foobar');
  // or can use
  // $guzzleResponse = $client->request('GET', '/foobar')
    if ($guzzleResponse->getStatusCode() == 200) {
         $response = json_decode($guzzleResponse->getBody(),true);
         //perform your action with $response 
    } 
}
catch(\GuzzleHttp\Exception\ServerException $se){
   // you can catch here 500 response errors
   // You can either use logs here you can use this package to handle logs https://github.com/Seldaek/monolog
   return $se->getMessage();
}catch(Exception $e){
   //other errors 
}

Similarly you can handle 400 exceptions using ClientException, see more about exceptions from docs.

Upvotes: 1

Related Questions