【发布时间】: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