Skip to content

Proposal: RetryHook with error handling #1007

@speedfl

Description

@speedfl

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions