【问题标题】:Error handling Web Api .net core and Repository Pattern错误处理 Web Api .net 核心和存储库模式
【发布时间】:2019-10-28 17:43:54
【问题描述】:

我对 web api 有疑问,Repository 可能是一个重复的问题。 但我试图搜索它,我没有得到任何满意的答案。 在我的存储库中,我在 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.
       }
}

【问题讨论】:

  • 在请求之前执行的管道中添加一个错误处理程序,该处理程序只是一个将执行代码包装在try catch中的类,然后只需处理每个错误并清除您没有的细节'不想发送给用户
  • @johnny5,感谢您的提示,非常感谢,您能否给我 c# 代码示例以更清楚地理解您的观点。

标签: httpclient asp.net-core-webapi repository-pattern


【解决方案1】:

你可以自定义一个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);
            }));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 2021-04-27
    • 2019-02-09
    • 1970-01-01
    • 2019-10-25
    • 2019-04-26
    相关资源
    最近更新 更多