Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

wdrleo's avatar

Guzzle 6 Catch HTTP Error and Retrieve Request

I'm doing request to api with Guzzle 6. I want catch HTTP 1.0 401 Unauthorized exception and retry request after get new token. But I can not find examples in the new version documentation. Events interface had in the old documentation but no event interface new version.

public function doSearch(Request $request)
{
   $apiData = API::where('id', '1')->first(['api_url', 'api_key']);
   try {
       $client = new Client([
           // Base URI is used with relative requests
           'base_uri'  =>  $apiData['api_url'],
           'timeout'   =>  60,
           'headers' => [
               'Authorization' =>  'bearer token',
               'Content-Type'  =>  'application/x-www-form-urlencoded',
           ],
           'verify'    => false,
       ]);

       $request = $client->request('POST', '/api/booking/ticket/search', [
           'RouteType' => $request->input('type')
       ]);
   } catch (ClientException $e) {
       die((string)$e->getResponse()->getBody());
   }
   $code = $request->getStatusCode(); // 200
   $test = $request->getBody()->getContents();
   //$test = json_decode($test,true);
   return view('front.searchresult');
}

I don't want catch with try-catch code block. I should to renew my desire to create an event listener.

How to catch HTTP Exception and renew request on Guzzle 6?

0 likes
1 reply

Please or to participate in this conversation.