[英]Web API filters not catching exceptions thrown from a method group
我正在使用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);
}
從文檔
您可以通過編寫異常過濾器來自定義 Web API 處理異常的方式。 當控制器方法拋出任何未處理的異常時,將執行異常過濾器[...]
問題是,如果您從 WebAPI 方法返回IEnumerable<T>
,則在序列化期間,當IEnumerable<T>
被迭代時,將發生錯誤。 這是Select
(以及大多數其他查詢運算符)的標准行為,它僅在迭代時調用傳遞給它的方法(在本例中為MakeFooFromBar
),因此在調用Select
時不會拋出異常,但會在很久以后拋出。
您可以添加一個.ToList
以導致在您的方法內發生異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.