Home > Article > Backend Development > How to Catch Exceptions from Guzzle?
Catching Exceptions from Guzzle
Introduction
When testing APIs using Guzzle, handling exceptions is crucial to ensure reliable and informative error reporting. However, catching exceptions within Guzzle can sometimes be challenging, as unhandled exception errors may persist.
Guzzle 3
To catch exceptions from Guzzle, follow these steps:
Troubleshooting
If you still encounter unhandled exception errors, try disabling exceptions for Guzzle by modifying the client creation process. For Guzzle 3:
$client = new \Guzzle\Http\Client($httpBase, array( 'request.options' => array( 'exceptions' => false, ) ));
This will allow you to retrieve all HTTP status codes without throwing exceptions.
Guzzle 5.3 and Guzzle 6
For Guzzle 5.3 and Guzzle 6, the procedure is slightly different:
Guzzle 5.3:
$client = new \GuzzleHttp\Client(['defaults' => [ 'exceptions' => false ]] );
Guzzle 6:
$client = new \GuzzleHttp\Client(['http_errors' => false]);
Handling HTTP Response Codes
Once exceptions are disabled, you can use the response object's getStatusCode() method to retrieve the HTTP response code. Handle expected codes accordingly, such as 200 for success, 304 for no change, or 404 for not found. If an unexpected code is encountered, consider throwing a custom exception.
The above is the detailed content of How to Catch Exceptions from Guzzle?. For more information, please follow other related articles on the PHP Chinese website!