错误处理 Web Api .net 核心和存储库模式

Error handling Web Api .net core and Repository Pattern

我有关于网络的问题 api 并且 Repository 可能是一个重复的问题。 但我试图搜索它,但没有得到任何满意的答案。 在我的存储库中,我在 httpclient 的帮助下获取数据。

我的问题是我的响应中可能出现错误,或者我可以获得所需的 json 数据,我可以将其映射到我的产品 class.I 正在返回 IEnumerable。

1) 如果出现错误,我如何将其冒泡到控制器并向用户显示错误。 2) Return MessageResponse 而不是 IEnumerable 并在控制器内部处理它。

什么是最好的方法。

enter code here
public interface IProduct{
    Task<IEnumerable<Product>> All();
} 

public class Product:IProduct
{
      public async Task<IEnumerable<Product>> All(){
          var ResponseMessage=//some response.
       }
}

你可以自定义一个ApiException用来获取响应的错误信息,在你的startup.cs中调用UseExceptionHandler,参考如下:

ProductRep

 public class ProductRep : IProduct
{
    private readonly HttpClient _client;
    public ProductRep(HttpClient client)
    {
        _client = client;
    }
    public async Task<IEnumerable<Product>> All()
    {
        List<Product> productlist = new  List<Product>();

        var response = await _client.GetAsync("https://localhost:44357/api/values/GetProducts");

        string apiResponse = await response.Content.ReadAsStringAsync();

        if (response.IsSuccessStatusCode == false)
        {
            JObject message = JObject.Parse(apiResponse);
            var value = message.GetValue("error").ToString(); 
            throw new ApiException(value);                
        }

        productlist = JsonConvert.DeserializeObject<List<Product>>(apiResponse);

        return productlist;
    }

    public class ApiException : Exception
    {
        public ApiException(string message): base(message)
        { }
    }
}

Startup.cs

app.UseExceptionHandler(a => a.Run(async context =>
            {
                var feature = context.Features.Get<IExceptionHandlerPathFeature>();
                var exception = feature.Error;

                var result = JsonConvert.SerializeObject(new { error = exception.Message });
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(result);
            }));