VOOZH about

URL: https://deepwiki.com/hypervel/http-client/8-error-handling-and-exceptions

⇱ Error Handling and Exceptions | hypervel/http-client | DeepWiki


Loading...
Menu

Error Handling and Exceptions

Purpose and Scope

This document covers the error handling and exception system in the Hypervel HTTP Client. It explains the exception hierarchy, throwing behavior, error callbacks, status checking methods, and strategies for handling HTTP errors (4xx, 5xx status codes) and connection failures.

For information about retry logic configuration, see Retry Logic and Error Recovery. For response status checking without exceptions, see Status Code Checking.


Exception Hierarchy

The library provides three exception classes that extend from a common base:



























Exception ClassNamespaceUse Case
HttpClientExceptionHypervel\HttpClient\HttpClientExceptionBase exception for all library errors
RequestExceptionHypervel\HttpClient\RequestExceptionHTTP error responses (4xx, 5xx status codes)
ConnectionExceptionHypervel\HttpClient\ConnectionExceptionNetwork/connection failures

Sources: src/HttpClientException.php1-12 src/RequestException.php1-62 src/ConnectionException.php1-10


Exception Types

HttpClientException

Base exception class for all HTTP client exceptions. Extends PHP's built-in Exception class.

Sources: src/HttpClientException.php9-11

RequestException

Thrown when an HTTP request completes but returns an error status code (4xx or 5xx). Contains the Response object and formats detailed error messages.

Property/MethodTypeDescription
$responseResponsePublic property containing the response that triggered the exception
$truncateAtfalse|intStatic property controlling message truncation (default: 120 characters)
getCode()intReturns the HTTP status code
getMessage()stringReturns formatted error message with response details

Static Configuration Methods:

MethodDescription
RequestException::truncate()Enable truncation at 120 characters
RequestException::truncateAt(int $length)Set custom truncation length
RequestException::dontTruncate()Disable truncation, show full response

Sources: src/RequestException.php1-62 src/Response.php283-290

ConnectionException

Thrown when an HTTP request fails to complete due to network or connection issues. Converted from Guzzle's ConnectException during request execution.

Common causes:

  • Network timeouts
  • DNS resolution failures
  • Connection refused errors
  • SSL/TLS handshake failures

Sources: src/ConnectionException.php1-10 src/PendingRequest.php773-782 </old_str> <new_str>

Exception Types

HttpClientException

Base exception class for all HTTP client exceptions. Located at Hypervel\HttpClient\HttpClientException and extends PHP's built-in Exception class. Catch this to handle any error originating from the library.

Sources: src/HttpClientException.php9-11

RequestException

Thrown when an HTTP request completes but returns an error status code (4xx or 5xx). The exception contains the full Response object and formats detailed error messages with configurable truncation.

Public Properties:


Static Properties:


Static Configuration Methods:


Exception Details:

  • getCode() returns the HTTP status code
  • getMessage() returns: "HTTP request returned status code {status}:\n{body_summary}\n"
  • Body summary uses GuzzleHttp\Psr7\Message::bodySummary() for intelligent truncation

Sources: src/RequestException.php9-62 src/Response.php283-290

ConnectionException

Thrown when an HTTP request fails to complete due to network or connection issues. Converted from Guzzle's ConnectException in the PendingRequest::send() method.

Common Causes:

  • Connection timeouts (exceeding connect_timeout or timeout values)
  • DNS resolution failures
  • Connection refused (server not listening)
  • SSL/TLS handshake failures

Conversion Process:

The library catches Guzzle's ConnectException and wraps it:


Sources: src/ConnectionException.php1-10 src/PendingRequest.php773-782 src/PendingRequest.php862-868


Exception Types

HttpClientException

The base exception class for all HTTP client exceptions. This can be caught to handle any error originating from the library.

ClassFile
Hypervel\HttpClient\HttpClientExceptionsrc/HttpClientException.php9-11

Sources: src/HttpClientException.php1-12

RequestException

Thrown when the HTTP request completes but returns an error status code (4xx client errors or 5xx server errors). This exception contains the full Response object and provides detailed error information.

Property/MethodTypeDescription
$responseResponseThe response object that triggered the exception
getCode()intReturns the HTTP status code
getMessage()stringReturns formatted error message with response details
$truncateAtfalse|intStatic property controlling message truncation length (default: 120)

The exception message includes the HTTP status code and a summary of the response body, which can be truncated for readability:


Truncation Control Methods:


Sources: src/RequestException.php1-62 src/Response.php281-290

ConnectionException

Thrown when the HTTP request fails to complete due to connection issues (network timeout, DNS resolution failure, connection refused, etc.). This is converted from Guzzle's ConnectException.

PropertyTypeDescription
Inherits fromHttpClientExceptionNo additional properties

Sources: src/ConnectionException.php1-10 src/PendingRequest.php773-782


Exception Flow in Request Execution


Sources: src/PendingRequest.php713-794 src/PendingRequest.php773-782 src/PendingRequest.php740-770


Configuring Throw Behavior

PendingRequest Throw Configuration

The PendingRequest class provides methods to configure when exceptions should be thrown for error responses:

Throw Configuration Methods:

MethodParametersDescription
throw()?callable $callback = nullEnable exception throwing on client/server errors
throwIf()bool|callable $conditionThrow if condition is true
throwUnless()bool|callable $conditionThrow if condition is false

Internal State:


Two properties control throwing behavior:

  • $throwCallback (line 98): ?Closure - Executed when throwing an exception
  • $throwIfCallback (line 103): ?Closure - Evaluates whether to throw

Throw Execution Logic:

In the request execution flow (line 752-757):


Usage Examples:


Sources: src/PendingRequest.php565-591 src/PendingRequest.php98-103 src/PendingRequest.php752-757

Response Throw Methods

The Response class provides granular control over when to throw exceptions:

MethodConditionThrows When
throw()Alwaysfailed() returns true
throwIf()ConditionalCondition is true AND failed() returns true
throwIfStatus()Status matchStatus equals/matches given value
throwUnlessStatus()Status mismatchStatus does not equal/match given value
throwIfClientError()4xx errorsclientError() returns true
throwIfServerError()5xx errorsserverError() returns true

Usage Examples:


Sources: src/Response.php297-373


Error Detection and Status Checking

The Response class provides methods to check response status without throwing exceptions. These methods are implemented in the DeterminesStatusCode trait, which is used by the Response class.


Status Checking Methods:

MethodReturnsImplementation
successful()bool$this->status() >= 200 && $this->status() < 300
redirect()bool$this->status() >= 300 && $this->status() < 400
clientError()bool$this->status() >= 400 && $this->status() < 500
serverError()bool$this->status() >= 500
failed()bool$this->serverError() || $this->clientError()

Additional Status Methods:

The DeterminesStatusCode trait also provides semantic methods for specific status codes (e.g., ok(), created(), accepted(), noContent(), notFound(), unauthorized(), etc.). See page 6.2 for complete documentation.

Sources: src/Response.php27-28 src/Response.php195-232


Error Callbacks

onError Callback

Execute custom logic when an error response is received without throwing an exception:


The callback is executed only when failed() returns true, allowing you to handle errors without interrupting the execution flow.

Sources: src/Response.php236-244

Throw Callback

Execute custom logic immediately before throwing an exception:


The throw callback receives both the Response object and the RequestException that will be thrown.

Sources: src/PendingRequest.php566-571 src/PendingRequest.php752-757


Integration with Retry Logic

The error handling system integrates with the retry mechanism. When retries are configured, the exception behavior changes:


Key Retry-Related Properties:

PropertyTypeDefaultDescription
$triesarray|int1Number of attempts
$retryDelayClosure|int100Milliseconds between retries
$retryThrowbooltrueThrow exception when all retries fail
$retryWhenCallback?callablenullCallback to determine if retry should occur

Behavior:

  1. If a request fails and retries are available, the exception is caught internally and the request is retried
  2. If retryWhenCallback returns false, retries are skipped and normal throw behavior applies
  3. After all retries are exhausted and retryThrow is true, a RequestException is thrown
  4. If retryThrow is false, the error response is returned without throwing

Sources: src/PendingRequest.php106-125 src/PendingRequest.php731-793 src/PendingRequest.php496-508


Connection Failure Handling

Connection failures are handled differently from HTTP errors. When a connection cannot be established, Guzzle throws a ConnectException, which is caught and converted to a ConnectionException.

Connection Failure Flow:


Synchronous Request Handling:

In PendingRequest::send() (lines 773-782), the library catches ConnectException:


Key Actions:

  1. Wraps Guzzle's ConnectException in ConnectionException
  2. Creates a Request object from the failed request
  3. Records the request with null response for test assertions
  4. Dispatches ConnectionFailed event (see page 7)
  5. Throws or allows retry logic to handle

Asynchronous Request Handling:

In PendingRequest::makePromise() (lines 862-874), connection failures are handled in the promise chain:


Retry Integration:

Connection exceptions are handled by the retry mechanism (configured via retry() method). The retry() helper function wraps the execution and catches exceptions, allowing retries based on:

  • Number of attempts configured in $tries
  • Delay configured in $retryDelay
  • Custom retry condition in $retryWhenCallback

See page 10.3 for detailed retry configuration.

Sources: src/PendingRequest.php773-782 src/PendingRequest.php862-868 src/PendingRequest.php731-793


Creating Exceptions from Responses

The Response class provides the toException() method to create a RequestException without throwing it:


This method returns null if the response was successful, making it safe to use in conditional chains:


Sources: src/Response.php281-290


Exception Message Formatting

The RequestException class formats error messages to include the HTTP status code and response body summary.

Message Format:

HTTP request returned status code {status}:
{response_summary}

Truncation Configuration:

The static property $truncateAt (line 14) controls message length:


Configuration Methods:


Implementation:

The prepareMessage() method (lines 51-60) formats the exception message:


The method uses Guzzle's Message::bodySummary() for intelligent truncation that:

  • Preserves important headers
  • Truncates body content at specified length
  • Adds ellipsis to indicate truncation

Sources: src/RequestException.php14-60


Error Handling Patterns

Pattern 1: Fail Fast

Throw exceptions immediately on any error:


Pattern 2: Conditional Error Handling

Handle errors only under specific conditions:


Pattern 3: Deferred Exception Handling

Check response and decide whether to throw:


Pattern 4: Callback-Based Error Handling

Execute custom logic before throwing:


Pattern 5: Silent Error Handling

Handle errors without exceptions:


Sources: src/PendingRequest.php565-591 src/Response.php236-244 src/Response.php297-373

Refresh this wiki

On this page