【问题标题】:Catch/translate exception from ASP.NET OData Get method从 ASP.NET OData Get 方法捕获/翻译异常
【发布时间】:2018-04-15 10:01:29
【问题描述】:

我使用 ASP.NET OData 库实现了 OData 服务。

所以,我有一个像这样的控制器:

public class ProjectsController : ODataController
{
    private readonly MyContext _db;

    public ProjectsController(MyContext db)
    {
        _db = db;
    }

    [EnableQuery]
    public IQueryable<Project> Get(string customQuery)
    {
        var query = _db.Projects;

        if (!string.IsNullOrWhitespace(customQuery))
        {
            query = query.Where(/* something complex going here */);
        }

        return query.OrderByDescending(p => p.Id);
    }

}

现在,这一切都很好。但是,在某些情况下,某些特定的“customQuery”可能会产生导致除以零的 SQL 代码。并且,作为结果,服务器发回状态 500 (oops) 和这样的错误对象:

{"error":{"code":"","message":"发生错误。"}}

这不是很丰富。我想捕获异常并将其翻译为 400 并带有一些有意义的消息(建议用户如何修复自定义查询)。

我试过设置全局异常过滤器,属性异常过滤器.. 没有运气。有什么想法吗?

【问题讨论】:

    标签: c# asp.net asp.net-web-api odata


    【解决方案1】:

    如果有人感兴趣,我可以实现我自己的 IExceptionHandler:

    class MyExceptionHandler : IExceptionHandler
    {
        public virtual Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
        {
            if (context.Request.Method == HttpMethod.Get && context.Request.RequestUri.AbsolutePath == "/odata/projects")
            {
                if (IsDivideByZero(context.Exception))
                {
                    const string message = "Division by zero encountered while applying the filter";
                    var response = context.Request.CreateResponse(HttpStatusCode.BadRequest, new HttpError(message));
                    context.Result = new ResponseMessageResult(response);
                }
            }
    
            return Task.CompletedTask;
        }
    
        private static bool IsDivideByZero(Exception ex)
        {
            if (ex is SqlException sqlEx && sqlEx.Number == 8134)
                return true;
    
            return ex.InnerException != null && IsDivideByZero(ex.InnerException);
        }
    }
    

    并像这样向 DI 注册它:

    private static void Configure(HttpConfiguration config)
    {
      // ...
      config.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler());
      // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-31
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多