【发布时间】:2017-09-06 14:24:41
【问题描述】:
我正在开发一个 ASP.NET Web API,在我的一个控制器操作中我使用了一个 Task.Factory.StartNew 调用。
但是,当任务内部抛出异常时,这不会触发我配置的异常过滤器。
Controller.cs
public class MyController : ApiController
{
[HttpPost]
public HttpResponseMessage Post()
{
Task.Factory
.StartNew(() => DoTheThing())
.ContinueWith(tsk => { throw new Exception("Webhook Exception", tsk.Exception); }, TaskContinuationOptions.OnlyOnFaulted);
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
ExceptionFilter.cs
public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new ObjectContent(typeof(object), new
{
Message = "Critical Error",
ExceptionMessage = "An error occurred, please try again or contact the administrator.",
Type = ExceptionType.Unhandled
}, new JsonMediaTypeFormatter()),
ReasonPhrase = "Critical Error"
});
}
}
Global.asax.cs
public class MyApplication : HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configuration.Filters.Add(new ExceptionFilter());
}
}
我可以调试并触发 ContinueWith 方法并抛出新的异常。但是过滤器没有被触发。
【问题讨论】:
-
您没有观察(重新)抛出的
Exception,因此它是Unobserved Exceptions。见:Task Exception Handling in .NET 4.5 -
感谢您的链接,我想我现在明白了这个问题。我正在尝试做不可能的事情,因为过滤器只会在我的操作中捕获异常。但我希望我的操作在我的任务结束前立即返回。
标签: c# asp.net asp.net-web-api