Home  >  Article  >  Backend Development  >  How Can I Avoid Unhandled Exceptions When Using Guzzle?

How Can I Avoid Unhandled Exceptions When Using Guzzle?

DDD
DDDOriginal
2024-11-02 08:25:02520browse

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,
   )
));

Guzzle 5.3

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

Guzzle 6

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

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

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

You can then handle different status codes accordingly:

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

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

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!

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