Home  >  Article  >  Backend Development  >  How to Handle Unhandled Exceptions in Guzzle When Testing APIs?

How to Handle Unhandled Exceptions in Guzzle When Testing APIs?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 06:27:02917browse

How to Handle Unhandled Exceptions in Guzzle When Testing APIs?

Resolving Unhandled Exceptions with Guzzle

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.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn