How to Handle Unhandled Exceptions in Guzzle When Testing APIs?

Patricia Arquette
Release: 2024-11-02 06:27:02
Original
916 people have browsed it

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,
   )
));
Copy after login

Guzzle 5.3

$client = new \GuzzleHttp\Client(['defaults' => [ 'exceptions' => false ]] );
Copy after login

With exceptions disabled, the HTTP status code can be obtained directly from the response.

$response = $request->send();
$statuscode = $response->getStatusCode();
Copy after login

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...");
}
Copy after login

Guzzle 6

In Guzzle 6, use 'http_errors' => false in the client options:

$client = new \GuzzleHttp\Client(['http_errors' => false]);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!