Skip to content

Error Handling

Igor Sazonov edited this page Feb 4, 2026 · 1 revision

Error Handling

Proper error handling is crucial for building robust and reliable applications. The Marketstack PHP SDK provides a clear and consistent way to handle API errors through a custom exception.

MarketstackException

When an API request fails, the package throws a Tigusigalpa\Marketstack\Exceptions\MarketstackException. This exception extends the base PHP Exception class and provides additional context about the error.

You can catch this exception to gracefully handle API errors, such as invalid API keys, rate limiting, or other issues.

use Tigusigalpa\Marketstack\Exceptions\MarketstackException;
use Tigusigalpa\Marketstack\Facades\Marketstack;

try {
    $data = Marketstack::eod()
        ->symbols('INVALID')
        ->collect();
} catch (MarketstackException $e) {
    // Log the error or display a user-friendly message
    echo "Error: {$e->getMessage()}";
    echo "Status Code: {$e->getCode()}";
}

Common Errors

Here are some common errors you might encounter:

Status Code Error Message Cause
404 not_found The requested resource could not be found.
401 invalid_access_key Your API key is incorrect or missing.
429 rate_limit_reached You have exceeded the number of allowed requests for your plan.
500 internal_server_error An error occurred on the Marketstack servers.

Rate Limiting

If you exceed the API rate limits for your subscription plan, the SDK will throw a MarketstackException with a 429 status code. You can handle this by implementing a retry mechanism with a delay, or by caching API responses to reduce the number of requests.

use Illuminate\Support\Facades\Cache;

try {
    $data = Marketstack::eod()->symbols('AAPL')->collect();
    Cache::put('aapl_price', $data, now()->addMinutes(15));
} catch (MarketstackException $e) {
    if ($e->getCode() === 429) {
        // Use cached data if available
        $data = Cache::get('aapl_price');
    } else {
        // Handle other errors
    }
}

For more advanced strategies, consider using a job queue to retry failed requests in the background.

Clone this wiki locally