resty icon indicating copy to clipboard operation
resty copied to clipboard

Proposal: RetryHook with error handling

Open speedfl opened this issue 10 months ago • 0 comments

Hello.

I observed that RetryHook does not support error handling.

Here is a simple use case:

I have an authentication that returns an access_token and a refresh_token.

When I get a 401 I need to retry by refreshing my token by calling the backend

Here is how I would do it:


client := resty.New().
    OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
        // Set your current token
        req.SetAuthToken(getCurrentToken())
        return nil
    }).
    SetRetryCount(1).
    AddRetryCondition(func(r *resty.Response, err error) bool {
        return r.StatusCode() == 401
    }).
    SetRetryHook(func(r *resty.Response, err error) {
        if r.StatusCode() == 401 {
            // Refresh token here
            refreshToken() 
        }
    })

But what if my refresh token fails ?

I would like to propose something like this:


client := resty.New().
    OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
        // Set your current token
        req.SetAuthToken(getCurrentToken())
        return nil
    }).
    SetRetryCount(1).
    AddRetryCondition(func(r *resty.Response, err error) bool {
        return r.StatusCode() == 401
    }).
    SetRetryHook(func(r *resty.Response, err error) error {
        if r.StatusCode() == 401 {
            // Refresh token here
            if err := refreshToken(); err != nil {
               return fmt.Errorf("error refreshing token, %w", err)
            }
            return nil
        }
    })

I can contribute if you want

speedfl avatar Apr 23 '25 08:04 speedfl