#1007·resty

Proposal: RetryHook with error handling

Author: speedflCreated Apr 23, 2025Updated Apr 23, 2025

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:

go

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:

go

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