防止 Guzzle 在非 200 响应时产生 500 错误

Prevent Guzzle from creating a 500 error on non 200 response

在我的网站上,我使用 Guzzle 向 AbuseIPDB 报告黑客攻击企图。例如,当黑客访问 /.env 时,报告将自动归档。当您针对同一 IP 发送多个报告时,AbuseIPDB 会返回 429。 Guzzle 然后给出 500 错误,因为 AbuseIPDB 没有给出 200 OK。

我的问题是,如何防止 Guzzle 在收到非 200 OK 响应时终止程序?可以这样做吗?

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.

我将添加一个示例来说明如何仅处理 500 个错误,

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 
}

同样,您可以使用 ClientException 处理 400 个异常,请参阅 docs.

中有关异常的更多信息