在我的C#Web API中,我試圖添加一個全局異常處理程序。我一直在使用一個自定義的全球ExceptionFilterAttribute
來處理異常,並返回一個HttpResponseMessage
:Web API OWIN啓動異常處理
public override void OnException(HttpActionExecutedContext context)
{
...
const string message = "An unhandled exception was raised by the Web API.";
var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(message),
ReasonPhrase = message
};
context.Response = httpResponseMessage;
}
這一直很好處理在控制器級別拋出異常。
但是,在開發過程中,由於數據庫連接問題,我們的OWIN啓動文件出現錯誤,但是,返回了標準IIS異常,而不是通過全局異常處理程序,並且完整的HTML返回我們的API消費者。
我已經嘗試了幾種不同的方法,以趕上我OWIN啓動拋出的異常:
定製ApiControllerActionInvoker
:
public class CustomActionInvoker : ApiControllerActionInvoker
{
public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
var result = base.InvokeActionAsync(actionContext, cancellationToken);
if (result.Exception != null && result.Exception.GetBaseException() != null)
{
...
}
return result;
}
}
定製ExceptionHandler
:
public class CustomExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
...
base.Handle(context);
}
public override bool ShouldHandle(ExceptionHandlerContext context)
{
return true;
}
}
定製OwinMiddleware
組件:
public class CustomExceptionMiddleware : OwinMiddleware
{
public CustomExceptionMiddleware(OwinMiddleware next) : base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch (Exception ex)
{
...
}
}
}
最後只用Application_Error
:
protected void Application_Error(object sender, EventArgs e)
{
...
}
但似乎沒有捕獲異常。
有誰知道一種方法來捕捉異常並返回HttpResponseMessage
?或者,如果我已經嘗試的任何方法應該工作?
任何幫助非常感謝。
如果這些都沒有工作,你可以訂閱的'AppDomain'.This的'UnhandledException'事件必須觸發一次有一種情況例外,有沒有適當的處理程序來處理異常。 –
感謝您的評論。我剛剛嘗試通過'Application_Start'方法添加訂閱'UnhandledException',但它似乎沒有捕獲。 'UnhandledException'確實可以通過Web API工作嗎? –
以及文檔說,這是在任何未處理的異常情況下必須觸發的事件。 –