Skip to content

Error Handling

Igor Sazonov edited this page Jul 15, 2026 · 1 revision

Nansen PHP provides a clear exception hierarchy for handling API errors gracefully. All exceptions thrown by the library extend Tigusigalpa\Nansen\Exceptions\NansenException.

Exception Hierarchy

The exception hierarchy is as follows:

  • NansenException (Base exception)
    • ApiException (Thrown for general API errors, HTTP 5xx)
      • RateLimitException (Thrown for HTTP 429 Too Many Requests)
      • UnauthorizedException (Thrown for HTTP 401 Unauthorized)
      • NotFoundException (Thrown for HTTP 404 Not Found)

Catching Exceptions

You can catch specific exceptions to handle different error scenarios.

use Tigusigalpa\Nansen\Exceptions\NotFoundException;
use Tigusigalpa\Nansen\Exceptions\RateLimitException;
use Tigusigalpa\Nansen\Exceptions\UnauthorizedException;
use Tigusigalpa\Nansen\Exceptions\ApiException;

try {
    $result = $client->profiler()->addressBalance('0x...')->get();
} catch (NotFoundException $e) {
    // The requested address or resource was not found.
    echo "Resource not found.\n";
} catch (RateLimitException $e) {
    // The rate limit was exceeded and all retries were exhausted.
    // You can access the Retry-After header value if provided by the API.
    echo "Rate limited. Try again in " . $e->retryAfter() . " seconds.\n";
} catch (UnauthorizedException $e) {
    // The API key is invalid or expired.
    echo "Authentication failed. Check your API key.\n";
} catch (ApiException $e) {
    // A general API error occurred (e.g., a 500 Internal Server Error).
    echo "API Error: " . $e->getMessage() . "\n";
}

Automatic Retries

The client automatically handles rate limits (HTTP 429) and transient server errors (HTTP 5xx) by retrying the request.

This behavior is controlled by the retries and retry_delay configuration options.

  • If a 429 response is received, the client will look for a Retry-After header. If present, it will sleep for that duration. If not, it uses an exponential backoff strategy based on the retry_delay.

  • If a 5xx response is received, it will use exponential backoff.

A RateLimitException or ApiException is only thrown if the maximum number of retries is exhausted.

Accessing the Response

If an exception is thrown as a result of an HTTP response (e.g., a 400 Bad Request), the original PSR-7 ResponseInterface object is attached to the exception. You can access it using the getResponse() method.

try {
    $client->smartMoney()->netflows()->get();
} catch (ApiException $e) {
    $response = $e->getResponse();
    
    if ($response) {
        echo "Status Code: " . $response->getStatusCode() . "\n";
        echo "Body: " . (string) $response->getBody() . "\n";
    }
}

Clone this wiki locally