Ich entwickle eine ASP.NET-Web-API, in einer meiner Controller-Aktionen verwende ich einen Task.Factory.StartNew-Aufruf.ExceptionFilterAttribute wird nicht ausgelöst, wenn Task.Factory.StartNew verwendet wird
Dies löst jedoch nicht den Ausnahmefilter aus, den ich konfiguriere, wenn eine Ausnahme in der Aufgabe ausgelöst wird.
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());
}
}
I kann debuggen und die ContinueWith-Methode wird ausgelöst und die neue Ausnahme wird ausgelöst. Aber der Filter wird nicht ausgelöst.
Sie beobachten nicht die (re) geworfene 'Exception', daher handelt es sich um eine' Unbeachtete Ausnahme'. Siehe: [Behandlung von Ausnahmebedingungen in .NET 4.5] (https://blogs.msdn.microsoft.com/pfxteam/2011/09/28/task-exception-handling-in-net-4-5/) – IronGeek
Danke für der Link, ich glaube ich verstehe das Problem jetzt. Ich versuche das Unmögliche möglich zu machen, da der Filter nur Ausnahmen in meiner Aktion abfängt. Aber ich möchte, dass meine Aktion unmittelbar vor dem Ende meiner Aufgabe zurückkehrt. – Joe