Home > Article > Backend Development > How to Handle Unhandled Exceptions in Guzzle When Testing APIs?
Catching exceptions while testing APIs with Guzzle can be challenging. This article addresses this issue and provides solutions for retrieving responses with non-200 HTTP codes.
In the example code, event listeners are used to handle specific HTTP codes, but exceptions are still being thrown. To resolve this, one option is to handle exceptions by HTTP status code.
For both Guzzle 3 and Guzzle 5.3, disabling exceptions allows for manual handling of all status codes. Simply set 'exceptions' => false in the client options.
Guzzle 3
$client = new \Guzzle\Http\Client($httpBase, array( 'request.options' => array( 'exceptions' => false, ) ));
Guzzle 5.3
$client = new \GuzzleHttp\Client(['defaults' => [ 'exceptions' => false ]] );
With exceptions disabled, the HTTP status code can be obtained directly from the response.
$response = $request->send(); $statuscode = $response->getStatusCode();
Expected status codes can be handled accordingly:
if (200 === $statuscode) { // Do something } elseif (304 === $statuscode) { // Nothing to do } elseif (404 === $statuscode) { // Clean up DB or something like this } else { throw new MyException("Invalid response from api..."); }
Guzzle 6
In Guzzle 6, use 'http_errors' => false in the client options:
$client = new \GuzzleHttp\Client(['http_errors' => false]);
The above is the detailed content of How to Handle Unhandled Exceptions in Guzzle When Testing APIs?. For more information, please follow other related articles on the PHP Chinese website!