我正在構建一個ASP.NET Web Api服務,我想創建集中的異常處理代碼。如何不在ASP.NET Web Api服務中拋出異常?
我想以不同的方式處理不同類型的異常。我將使用log4net記錄所有異常。對於某些類型的例外,我將通過電子郵件通知管理員。對於某些類型的例外,我想重新拋出一個友好的異常,並將其返回給調用者。對於某些類型的例外,我想繼續從控制器進行處理。
但我該怎麼做?我正在使用一個例外過濾器屬性。我有這個代碼工作。該屬性已正確註冊並且代碼正在觸發。我只想知道如果拋出某些類型的異常,我該如何繼續。希望這是有道理的。
public class MyExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
//Log all errors
_log.Error(myException);
if(myException is [one of the types I need to notify about])
{
...send out notification email
}
if(myException is [one of the types that we continue processing])
{
...don't do anything, return back to the caller and continue
...Not sure how to do this. How do I basically not do anything here?
}
if(myException is [one of the types where we rethrow])
{
throw new HttpResponseException(new HttpResponseMessage(StatusCode.InternalServerError)
{
Content = new StringContent("Friendly message goes here."),
ReasonPhrase = "Critical Exception"
});
}
}
}
異常過濾器僅在WebAPI消息管道的「返回」部分中被觸發。所以,如果你依靠異常過濾器來處理你的異常,我不認爲有一個簡單的方法讓請求重新進入管道進行進一步處理。有關WebAPI擴展點的更多信息,請參閱[MVC海報](http://www.asp.net/posters/web-api/ASP.NET-Web-API-Poster.pdf)。 –