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] Http Client: provide pending request to retry callback #41779

Merged

Conversation

gdebrauwer
Copy link
Contributor

In a couple of our projects, we are using the retry method of the Http Client to handle authentication errors. If a 401 error is thrown, we request a new token and then retry.
To achieve this, we currently have to manually create a request variable and pass the variable inside the closure in order to modify the request and set a new token on the request.

($request = Http::baseUrl(...))
  ->withToken($this->getToken())
  ->retry(2, 0, function ($exception) use ($request) {
      if ($exception->response->status() !== 401) {
          return false;
      }
  
      $request->withToken($this->getNewToken());
  
      return true;
  })
  ->get('...');

This PR allows you to access the request as a parameter of the closure:

Http::baseUrl(...)
  ->withToken($this->getToken())
  ->retry(2, 0, function ($exception, $request) { 
      if ($exception->response->status() !== 401) {
          return false;
      }
  
      $request->withToken($this->getNewToken());
  
      return true;
  })
  ->get('...');

@taylorotwell
Copy link
Member

@gdebrauwer It seems surprising to me that this works. Aren't the options given to sendRequest already built? I wouldn't expect modifying the request to actually change them.

@gdebrauwer
Copy link
Contributor Author

The sendRequest method is called every time the request is retries. The $options array paramer only contains querystring data or request body data. It merges that $options array with $this->options in the sendRequest method. Methods on the PendingRequest, like the withToken method, make changes to that $this->options array, so that's why it works 🙂

@taylorotwell
Copy link
Member

@gdebrauwer can you resolve the conflicts on this PR?

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