简体   繁体   中英

Refactor suggestion for C# try catch with server async Task return

About the method

  1. It is supposed to post data to the server side when session is valid.
  2. [Check Session Locally] - [Refresh] - [Send Data]
  3. [if 401 happens] - [Refresh] - [Send Data]

I'm not sure about

  1. If there is any redundancy in the "IF" condition and "try-catch" block, that could be simplified.
  2. Also, not familiar with the Task and async stuff, is the way that put the "PendRefresh" task inside correct or appropriate?

Appreciated for any suggestion!

private async Task<TResult> PostRequestAsync<TResult>(ServerRequest request)
{
    //check if expired on client side
    if (LocalHelper.IsExpired(request))
    {
        request.Token = await PendRefresh().ConfigureAwait(false);      //[Refresh]
    }

    try
    {
        return await PostServerAsync<TResult>(request).ConfigureAwait(false);   //[Send Data]
    }
    catch (ServerException e)
    {
        //session expired on the server side
        if (e.Code == HttpStatusCode.Unauthorized)
        {
            request.Token = await PendRefresh().ConfigureAwait(false);              //[Refresh]
            return await PostServerAsync<TResult>(request).ConfigureAwait(false);   //[Send Data]
        }
    }
    return default;

    //Q2, is this OK?
    async Task<string> PendRefresh()
        {
        //something here
    }
}

Edit:

added a simple flow there

simple img

What you have now is at least very readable.

You are repeating yourself a bit with the "refresh" and "send data" but given that I can see all of the workflow and failure points in one screen, I value that more than a more generic approach.

The only reason I would change this is if the refresh or send data functions became non-trivial and interfered with understanding the authentication workflow.

If you do want to re-architect this as an exercise, I think the technique you're looking for is a " continuation task ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM