2011-04-20 45 views
2

我很新的MVC ASP.NET。我讀了關於OnException覆蓋方法。我在想,我是否應該把catch {throw}放在Controller或Model上,以便調用OnException。或者,我嘗試捕獲不需要,如果發生任何異常OnException將被自動調用?ASP.NET MVC OnException - 嘗試捕獲所需?

謝謝堆。

回答

2

「在動作發生未處理的異常時調用。」

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onexception.aspx

如果你不處理(即「捕獲」)例外,onException的方法應該被調用。

+0

謝謝。現貨,所以我應該刪除所有我嘗試抓住它只是拋出異常泡沫了嗎? – 2011-04-20 23:32:06

+1

@flybyte:這取決於你正在做什麼,你試圖捕捉的例外。但是,是的,最好的策略通常或者是在最高可能級別('OnException')之前不捕獲異常,或者使用原始異常作爲InnerException來拋出一個帶有額外上下文信息的新異常。 – StriplingWarrior 2011-04-20 23:37:45

1

我結束了這樣做:

使用抽象類FilterAttribute和如下所示實現個IExceptionFilter創建LogAndRedirectOnErrorAttribute類:

public class LogAndRedirectOnErrorAttribute : FilterAttribute,IExceptionFilter 
    { 
     public void OnException(ExceptionContext filterContext) 
     { 
      //Do logging here 
      Util.LogError(Utility.GetExceptionDetails(filterContext.Exception), TraceEventType.Critical.ToString()); 

      //redirect to error handler 
      filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
       new { controller = "Error", action = "Index" })); 

      // Stop any other exception handlers from running 
      filterContext.ExceptionHandled = true; 

      // CLear out anything already in the response 
      filterContext.HttpContext.Response.Clear(); 
     } 
    } 

並在每個控制器類在必要時,使用上面的屬性:

[LogAndRedirectOnError] 
public class AccountController:Controller 
{ 
..... 
} 
+0

過濾器實現非常整齊。你有沒有考慮過爲你的控制器創建一個基類來從中得到適用的過濾器?這將減少過濾器屬性的使用。您也可以將記錄器依賴項傳遞給基類構造函數,理想的情況是將其作爲接口並使用IoC容器來處理構建邏輯。 – 2013-02-16 06:53:07

+0

您可以簡單地將該屬性添加爲過濾器,以便默認情況下它將在所有控制器上:\t \t \t filters.Add(new LogAndRedirectOnErrorAttribute()); 在這個處理程序中包含重定向也是值得懷疑的,因爲您可以使用已經內置的customErrors功能,並讓它可配置。 – 2016-04-11 21:19:58