Home > database >  Refit - ApiResponse<T> wrapping in a methods cannot get access to content
Refit - ApiResponse<T> wrapping in a methods cannot get access to content

Time:09-22

I am using refit and works great but I am also new to it.

I have the need to wrap up ApiResponse in a call (see below) because within this method I will do things like

  • Logging
  • Handling exceptions
  • etc.. but I cannot make it work as its null!!

Caller

   var response = await ExecuteAsync(() => webApiClient.GetStuff());

Method where apiresponse is null

public async Task<T> ExecAsync<T>(
        Func<Task<T>> method) where T : class
    {
       T apiResponse = await method.Invoke();
        ApiResponse<T> apiResponseOfT =apiResponse as ApiResponse<T>;//this is null
        if (apiResponseOfT.IsSuccessStatusCode)
        {
            //do other stuff
            return apiResponse;
        }
        else
        {
            //do some logging etc..
            return apiResponse;
        }
    }

What Am I doing wrong - Why is it null? Is it possible to return just the apiResponse.Content?

How do I wrap up ApiResponse in an ExecAsync?

Updated

See below to give more context ...

    [Get("/api/v1/customers")]
    Task<ApiResponse<GetCustomerResponse>> GetCustomers();
    
    public class GetCustomerResponse:ResponseBase
    {
        //various properties here...
    }
     public abstract class ResponseBase
    {
          public bool IsSuccess { get; set; }
    }
    
    
    ApiResponse<GetCustomerResponse> response = await ExecuteAsync(() => webApiClient.GetCustomers())

CodePudding user response:

Change the declaration to public async Task<ApiResponse<T>> ExecAsync<T>(Func<Task<ApiResponse<T>>> method) where T : class and changing the implementation accordingly should do. Something like

public async Task<ApiResponse<T>> ExecAsync<T>(
    Func<Task<ApiResponse<T>>> method) where T : class
{
    var apiResponseOfT = await method();
    if (apiResponseOfT.IsSuccessStatusCode)
    {
        //do other stuff
        return apiResponse;
    }
    else
    {
        //do some logging etc..
        return apiResponse;
    }
}

If you are not planning to throw any exception, you can just return after if-else instead.

  • Related