How can one properly handle exceptions, such as HTTPException 404, when using GuzzleHttp in PHP?
When using GuzzleHttp in PHP, you can handle exceptions like HTTPException 404 by catching the exception and then handling it accordingly in your code. This can be done using a try-catch block where you catch the specific exception and then perform the necessary actions, such as logging the error or displaying a custom message to the user.
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$client = new Client();
try {
$response = $client->request('GET', 'http://example.com/api');
// Process the response
} catch (RequestException $e) {
if ($e->getResponse()->getStatusCode() == 404) {
// Handle 404 error
echo "404 Not Found";
} else {
// Handle other errors
echo "An error occurred: " . $e->getMessage();
}
}