Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Pass thrown exception to $sleepMilliseconds closure in retry helper #42532

Merged
merged 1 commit into from
May 26, 2022

Conversation

arondeparon
Copy link
Contributor

What does this pull request implement?

This pull requests implement a backwards-compatible change to the retry helper. The retry helper accepts either an int or a Closure. When passing a Closure object, the $attempts parameter would be passed, allowed users to implement their own backoff algorithm.

In some cases, however, it would be desirable to implement a backoff strategy based on the exception that was thrown, for example in the case of an API client that returns a specific exception in the case of a HTTP 429. In such cases, the exception thrown could potentially hold information as to how long a user has to wait before a new attempt will be excepted.

This pull request allows you to access the thrown exception instance in the $sleepMilliseconds closure to implement a dynamic backoff strategy.

Example use case

Imagine an API library that throws the following exception in the case of a HTTP 429:

<?php

class TooManyRequestsException extends ApiException
{
    public int $retryAfterNumberOfSeconds;

    public int $currentRateLimit;

    public int $rateLimitResetsAfterTimestamp;
}

Using the above information, we would be able to implement a dynamic backoff strategy as follows:

retry(3, function() {
    // Perform some kind of external API call
}, function($attempts, $exception) {
    // Use the information provided by the external API to provide `rescue` with a dynamic delay
    return $exception->retryAfterNumberOfSeconds / 1000;
});

@taylorotwell taylorotwell merged commit b34d67a into laravel:9.x May 26, 2022
@GrahamCampbell GrahamCampbell changed the title Pass thrown exception to $sleepMilliseconds closure in retry helper [9.x] Pass thrown exception to $sleepMilliseconds closure in retry helper May 27, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants