Catching exceptions from Guzzle

Catching exceptions from Guzzle

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Catching exceptions from Guzzle

When building APIs, handling failures gracefully is essential for observability and resilience. Using Guzzle to consume these services often leads to unexpected behavior when HTTP errors occur. A common scenario involves wrapping requests in a try/catch block, only to encounter unhandled exceptions even after attempting to intercept them with event listeners. The issue typically stems from how Guzzle propagates errors and the specific types of exceptions thrown for different HTTP status codes.

In many cases, developers assume that any non-200 response will be caught by a generic Exception or a broad catch block. However, Guzzle is designed to throw specific exception classes based on the HTTP status code returned by the server. For instance, a 401 Unauthorized response triggers a Guzzle\Http\Exception\ClientErrorResponseException, while a 500 Internal Server Error might trigger a ServerErrorResponseException. If your code attempts to catch only generic exceptions or relies solely on event listeners without proper propagation control, these specific exceptions will bypass your handlers and crash the application.

To resolve this, you must ensure that your exception handling logic explicitly accounts for the specific Guzzle exception classes corresponding to the status codes you expect to encounter. Simply adding an event listener with stopPropagation() is not enough if the exception is already being thrown before the response is processed or if the listener does not prevent the default error handling flow.

Consider a scenario where you are iterating through a set of API tests. Each request should be wrapped in a try-catch block that handles specific HTTP error types. Below is an example of how to structure this logic correctly:

foreach ($tests as $test) {
    $client = new GuzzleHttp\Client(['base_url' => $api_url]);

    // Configure default options if necessary
    $query_string = ['key' => 'value']; 

    try {
        $request = $client->get($api_version . $test['method'], [
            'query' => isset($test['query']) ? $test['query'] : []
        ]);

        $response = $request->send();
        
        // Handle successful responses
        displayTest($request, $response);
    } catch (GuzzleHttp\Exception\ClientException $e) {
        // This catches 4xx errors like 401, 400, 404
        $status = $e->getResponse()->getStatusCode();
        
        if ($status === 401) {
            // Handle unauthorized specifically here
            displayTest($e->getRequest(), $e->getResponse());
        } else {
            displayTest($e->getRequest(), $e->getResponse());
        }
    } catch (GuzzleHttp\Exception\ServerException $e) {
        // This catches 5xx errors like 500
        displayTest($e->getRequest(), $e->getResponse());
    } catch (\Exception $e) {
        // Fallback for unexpected errors
        echo "AGH!";
    }

    unset($client);
}

In this implementation, ClientException is thrown for 4xx status codes, while ServerException handles 5xx codes. These classes are part of the Guzzle HTTP library and are automatically instantiated by the client when an error response is received. By catching these specific exceptions, you can inspect the response object within the catch block to determine the appropriate action, such as logging the error or retrying the request.

It is important to note that event listeners registered via $client->getEventDispatcher()->addListener('request.error', ...) may not intercept exceptions if they are thrown after the listener has already completed its execution or if the exception is propagated directly by the library's internal logic. Relying on explicit exception types in your catch blocks is a more robust approach than trying to manipulate events for error handling purposes.

Additionally, always ensure that you access the response object safely within the catch block using $e->getResponse(). While Guzzle guarantees that a response object exists when these exceptions are thrown, it is good practice to verify the status code before making assumptions about the nature of the error. This approach ensures that your application remains stable and provides detailed feedback on what went wrong without crashing unexpectedly.

Our network