【问题标题】:Web API filters not catching exceptions thrown from a method groupWeb API 过滤器未捕获从方法组抛出的异常
【发布时间】:2018-02-16 14:24:19
【问题描述】:

我正在使用WebApi。我的基本控制器上有一个自定义ActionFilter,并在全球范围内添加了一个自定义ExceptionFilter。两者都继承自 System.Web.Http.Filters 命名空间中关联的 FilterAttributes,而不是 mvc 版本。

我的一个服务中的私有方法引发了异常,当在 Linq 语句(在本例中为 select)中使用此方法时,resharper 将其称为方法组。

public IEnumerable<Foo> GetFoos()
{
    IEnumerable<Bar> bars = _work.BarRepository.GetAll();

    //throw new Exception("I'm visible to the filters");

    IEnumerable<Foo> foos = bars.Select(MakeFooFromBar);

    return foos;
}

private Foo MakeFooFromBar(Bar bar)
{
    // an exception is being thrown here
    // which is not being caught by the filers
    throw new Exception("I am invisible to the filters");
}

这两个过滤器都没有捕捉到这个异常(见下面的过滤器)。我的操作过滤器说没有异常,我的异常过滤器从未被命中。如果我在 Linq 选择(我已注释掉的那个)之前抛出异常,那么异常会按预期捕获。

使用提琴手,我最终得到的是:

{  
   "message":"An error has occurred.",
   "exceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
   "exceptionType":"System.InvalidOperationException",
   "stackTrace":null,
   "innerException":{  
      "message":"An error has occurred.",
      "exceptionMessage":"I am invisible to the filters",
      "exceptionType":"System.Exception",
      "stackTrace":""
   }
}

我的操作过滤器的一部分:

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    Exception exception = actionExecutedContext.Exception;

    if (exception == null)
    {
        // do things
    }
    else
    {
        // do some other things
    }
}

以及我的异常过滤器的一部分:

public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
    // return early on certain kinds of exceptions...

    _loggedErrorService.Log(actionExecutedContext.Exception);
}

【问题讨论】:

    标签: c# linq asp.net-web-api exception-handling asp.net-web-api-filters


    【解决方案1】:

    来自documentation

    您可以通过编写异常过滤器来自定义 Web API 如何处理异常。当控制器方法抛出任何未处理的异常[...]

    时执行异常过滤器

    问题是如果你从你的WebAPI方法返回一个IEnumerable&lt;T&gt;,在序列化过程中,当IEnumerable&lt;T&gt;被迭代时,就会出现错误。这是Select(和大多数其他查询运算符)的标准行为,它只调用在迭代时传递给它的方法(在这种情况下为MakeFooFromBar),所以当你调用Select时不会抛出异常,但是很多稍后。

    您可以添加.ToList 以使异常在您的方法中发生。

    【讨论】:

    • 谢谢,我不知道这种行为。返回 IList 而不是 IEnumerable 是否是标准做法?
    • @JackPettinger 我不一定会更改返回类型,调用者只需要迭代结果,而不是使用任何其他方法。我唯一要改变的是IEnumerable,这是一个IEnumerable,它由内存中的集合而不是LINQ查询支持,它仍然需要执行非平凡的代码来获得结果。
    猜你喜欢
    • 1970-01-01
    • 2014-01-16
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多