PHP Guzzle Default Behavior Can Break Your App

Guzzle is a popular HTTP Client written in PHP, really popular actually with nearly 10,000 stars on github, over 400 watchers, and 37 million installs through composer. We use it in our application extensively when integrating third party REST APIs.

I discovered an issue with its standard behavior. By default, Guzzle will throw an exception if the resource you are connecting to is unavailable. You can easily replicate by forcing a 404 via GET or POST to a non-existent URL. This can be problematic in applications like ours which connect to other APIs before returning data to users of our own.

Above we connect to three APIs, but say our connection to the second fails on a 500 error. Our application would stop executing at that point. A failure to one of our integrations shouldn’t crater the entire request. Be sure to use the http_errors option parameter, this will prevent Guzzle from automatically throwing exceptions.

Now we can continue on to other parts of our code and handle non-200 response codes as needed. This will not take care of exceptions generated by PHP-cURL, for that you will need to wrap calls to GuzzleHttp in a try/catch statement.

Show your support

Clapping shows how much you appreciated Chris’s story.