8000 Question: generic response processor · Issue #531 · reactiveui/refit · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Question: generic response processor #531
Closed
@hiraldesai

Description

@hiraldesai

I'm using dotnet core HttpClientFactory and Refit together (and loving it!). This is not a dotnet core related question but here is what I'm trying to do.

Imagine the following API - except it has many different methods and return types other than string and int as per the example.

public interface ISomeApi
{
    [Get("/string")]
    Task<string> GetString();

    [Get("/int")]
    Task<int> GetInt();
}

public class ErrorResponse
{
    public string SomeErrorProperty { get; set; }
}

public class Test
{
    private readonly ISomeApi _someApi;

    public Test(ISomeApi someApi)
    {
        _someApi = someApi;
    }

    public async Task<SomeApiResponse<string>> TestString()
    {
        var result = new SomeApiResponse<string>();

        try
        {
            var stringValue = await _someApi.GetString();
            result.StatusCode = 200;
            result.Data = stringValue;
        }
        catch (ApiException e)
        {
            var error = e.GetContentAs<ErrorResponse>();
            result.StatusCode = (int) e.StatusCode;
            result.Error = error;
        }    

        return result;
    }

    public async Task<SomeApiResponse<int>> TestInt()
    {
        var result = new SomeApiResponse<int>();

        try
        {
            var intValue = await _someApi.GetInt();
            result.StatusCode = 200;
            result.Data = intValue;
        }
        catch (ApiException e)
        {
            var error = e.GetContentAs<ErrorResponse>();
            result.StatusCode = (int) e.StatusCode;
            result.Error = error;
        }

        return result;
    }
}

public class SomeApiResponse<T>
{
    public int StatusCode { get; set; }
    public T Data { get; set; }
    public ErrorResponse Error { get; set; }
}

I want to avoid having to write the catch (ApiException e) everywhere and just change the signature of my APIs to be something like this. Is it possible to do by somehow intercepting the HttpResponseMessage in one place? Like a custom DelegatingHandler but it executes fairly late in the process.

public interface ISomeApi
{
    [Get("/string")]
    Task<SomeApiResponse<string>> GetString();

    [Get("/int")]
    Task<SomeApiResponse<int>> GetInt();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0