skip to Main Content

I’m making a set of HTTP requests using Laravel’s Http::pool like so:

$responses = Http::pool(fn(Pool $pool) => $requests->map(fn($r) => 
            $pool->as($r->id)->myMacro()->post('myUrl', [
               ...
            ])
        ));

myMacro() is defined in AppServiceProvider like so:

        PendingRequest::macro('myMacro', function () {
            return PendingRequest::withHeaders([
                'Content-Type' => 'application/json',
                'Authorization' => ...
            ]);
        });

I would like to amend myMacro() to set up a standard retry policy for the service I’m calling. I want to retry on both errors and certain HTTP status codes (e.g. 503).

I can’t seem to get it to work, though. I tried calling withMiddleware in the macro to throw on certain status codes but the middleware was never invoked.

This feels like a straightforward ask; what am I doing wrong?

2

Answers


  1. This is how I’m doing it, try to change:

        PendingRequest::macro('myMacro', function () {
            return PendingRequest::withHeaders([
                'Content-Type' => 'application/json',
                'Authorization' => ...
            ]);
        });
    

    to this:

    use IlluminateHttpClientPendingRequest;
    use IlluminateHttpClientResponse;
    
    PendingRequest::macro('myMacro', function () {
        return $this->withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => ...
        ])->retry(3, 100, function ($response, $e) {
            // Retry on server error status codes or exceptions
            return $e instanceof Exception || ($response instanceof Response && $response->status() === 503);
        });
    });
    
    Login or Signup to reply.
  2. I guess you can use the retry method to retry a request based on certain conditions.You can modify your macro to include a retry:

    PendingRequest::macro('myMacro', function () {
        return PendingRequest::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => ...
        ])->retry(3, 100)->retryUntil(function ($response) {
            // Retry on server errors and 503 status code, etc...
            return $response->serverError() || $response->status() === 503;
        }, 100);
    });
    

    The request will be retried up to 3 times if it encounters a server error (5xx status code) or a 503 status code and there will be a 100ms delay between each attempt.
    I hope this is what you’re looking for…

    Edit:
    I modify it to use retryUntil instead

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search