8
ASP.NET Web API中是否有任何方式將異常標記爲在ExceptionFilterAttribute中處理?在Web API中處理設置異常ExceptionFilterAttribute
我想用異常過濾器在方法級別處理異常,並停止傳播到全局註冊的異常過濾器。
過濾器上的控制器動作中使用:
public class MethodExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotImplementedException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(context.Exception.Message)
};
// here in MVC you could set context.ExceptionHandled = true;
}
}
}
的全局註冊過濾器:
public class GlobalExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is SomeOtherException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.SomethingElse)
{
Content = new StringContent(context.Exception.Message)
};
}
}
}
你可以把你的「處理例外過濾器在方法級別的異常」樣本? – giacomelli 2013-05-08 14:25:17
爲了進入全局過濾器,我首先想到了方法中的異常處理方法 - 爲什麼不將不安全的代碼封裝在try/catch塊中並在那裏處理呢? – 2013-05-08 19:48:01
已添加示例。 – adamwtiko 2013-05-10 07:42:55