Skip to content

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

Merged
taylorotwell merged 1 commit intolaravel:9.xfrom
arondeparon:9.x
May 26, 2022
Merged

[9.x] Pass thrown exception to $sleepMilliseconds closure in retry helper#42532
taylorotwell merged 1 commit intolaravel:9.xfrom
arondeparon:9.x

Conversation

@arondeparon
Copy link
Copy Markdown
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