Skip to content
Advertisement

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?

Advertisement

Answer

A GuzzleHttpExceptionServerException is thrown for 500 level errors if the http_errors request option is set to true. This exception extends from GuzzleHttpExceptionBadResponseException.

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

try{
  $client = new GuzzleHttpClient(['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(GuzzleHttpExceptionServerException $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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement