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

Possible to get retryCount from afterResponse() or beforeError() hooks #511

Open
priithansen opened this issue Jun 7, 2023 · 2 comments

Comments

@priithansen
Copy link

I would like to show a notification to users on 5xx errors but as it is now I can't figure out a way to avoid showing it for only the last retry.

The code could live in either afterResponse or beforeError hook and from there I can get the current retry config ex: error.options.retry.limit but as far as I can tell no way to know if the request in question is last retry in the series.

Thank You for this useful and to the point library.

@sindresorhus
Copy link
Owner

I guess we could add the current retry count to the error given to beforeError.


Ideally, Ky would support some kind of mutable context (like Got) which would let you add this property in beforeRetry and read it in any of the hooks. But it's probably worth waiting for Async Context.

@priithansen
Copy link
Author

Context indeed sounds more flexible then trying to cater for every possible use case people come up with.

As I started to implement a interim solution for this as seen below I soon realised it's not even retry count I'm after so much as how many retries there are left. As the retry count can depend on many parameters besides retry limit like status code, method and the retry-after header logic. Not sure if the Ky internal state even has that info clearly available or it can change depending on each retry timing and headers.

For now my imperfect implementation is as follows:

beforeRetry: [
  async ({ request, options, error, retryCount }) => {
    request.headers.set('x-my-app-retry', retryCount.toString())
  },
],
afterResponse: [
  async (request, options, response) => {
    if (response.status >= 500 && response.status <= 599) {
      if (
        // Either request does not fall into retry bracket or make sure it is the last retry.
        (options.retry.statusCodes && options.retry.statusCodes.indexOf(response.status) === -1) ||
        (options.retry.limit || 1) - 1 === Number(request.headers.get('x-my-app-retry'))
      ) {
        toastController.present({ ... })
      }
    }
  },
],

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

No branches or pull requests

2 participants