How Can I Avoid Unhandled Exceptions When Using Guzzle?

DDD
Release: 2024-11-02 08:25:02
Original
519 people have browsed it

How Can I Avoid Unhandled Exceptions When Using Guzzle?

Avoid Unhandled Exceptions with Guzzle

When testing APIs, it's crucial to handle HTTP errors to prevent exceptions from halting execution. Guzzle provides ways to catch these exceptions, but sometimes your code may still encounter unhandled exceptions.

The issue you're facing can be resolved by disabling exceptions for Guzzle. This allows you to handle the status codes manually without exceptions interfering. Here's how to achieve this:

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

Guzzle 6

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

Once exceptions are disabled, you can retrieve the HTTP status code from the response:

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

You can then handle different status codes accordingly:

if ($statuscode > 300) {
  // Do some error handling
}
Copy after login

Or handle specific expected codes:

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

By disabling exceptions and handling status codes manually, you can have full control over error handling and prevent interruptions in your test execution.

The above is the detailed content of How Can I Avoid Unhandled Exceptions When Using Guzzle?. 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
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!