To handle GuzzleClient errors, you can use the following techniques:
- Catch exceptions: GuzzleClient throws exceptions for HTTP errors. You can catch these exceptions and handle them accordingly.
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$client = new Client(['base_uri' => 'https://api.example.com']);
try {
$response = $client->request('GET', '/endpoint');
} catch (RequestException $e) {
// Handle the exception
echo "Error message: " . $e->getMessage();
// Get the response if available
if ($e->hasResponse()) {
$response = $e->getResponse();
echo "Status code: " . $response->getStatusCode();
}
}
- Use
http_errors option: By default, Guzzle will throw exceptions for 4xx and 5xx status codes. You can set the http_errors option to false to disable this behavior and handle errors manually.
use GuzzleHttp\Client;
$client = new Client(['base_uri' => 'https://api.example.com']);
$response = $client->request('GET', '/endpoint', ['http_errors' => false]);
// Check the status code and handle errors
$status_code = $response->getStatusCode();
if ($status_code >= 400) {
// Handle the error
echo "Error: " . $status_code;
}
- Use middleware: You can use Guzzle middleware to intercept and handle errors before they are thrown as exceptions. This can be useful for more complex error handling scenarios.
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
$handler_stack = HandlerStack::create();
$handler_stack->push(Middleware::mapRequest(function (RequestInterface $request) {
return $request;
}));
$handler_stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
$status_code = $response->getStatusCode();
if ($status_code >= 400) {
// Handle the error
echo "Error: " . $status_code;
// Optionally, you can return a new response instead of throwing an exception
// return new_response;
}
return $response;
}));
$client = new Client(['base_uri' => 'https://api.example.com', 'handler' => $handler_stack]);
$response = $client->request('GET', '/endpoint');
Choose the appropriate error handling method based on your specific requirements and the complexity of your error handling logic.