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

问题描述 投票:0回答:1

我对Web api和存储库有疑问,可能是重复的问题。但是我试图对其进行搜索,但没有得到满意的答复。在我的存储库中,我正在借助httpclient获得数据。

我的问题是,我的响应中可能会出错,或者我可以获取所需的json数据,这些数据可以映射到我的产品类。我正在返回IEnumerable。

1)如果出现错误,如何将其冒泡到控制器并向用户显示错误。2)返回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.
       }
}
httpclient asp.net-core-webapi repository-pattern
1个回答
0
投票

您可以自定义用于获取响应错误消息的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);
            }));
© www.soinside.com 2019 - 2024. All rights reserved.