Asp.net-Mvc

如何在 ASP.NET MVC 3 應用程序中處理未擷取的異常?

  • July 6, 2011

我想在我的 ASP.NET MVC 3 應用程序中處理未擷取的異常,以便我可以通過應用程序的錯誤視圖將錯誤傳達給使用者。如何攔截未擷取的異常?我希望能夠在全球範圍內執行此操作,而不是針對每個控制器(儘管我也不介意知道如何執行此操作)。

您可以在中設置全域錯誤過濾器Global.asax

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
   filters.Add(new HandleErrorAttribute());
}

上面設置了一個預設錯誤處理程序,它將所有異常都定向到標準錯誤視圖。錯誤視圖被鍵入到System.Web.Mvc.HandleErrorInfo公開異常詳細資訊的模型對像中。

您還需要在 web.config 中打開自定義錯誤才能在本地電腦上看到它。

<customErrors mode="On"/>

您還可以為特定的錯誤類型定義多個過濾器:

filters.Add(new HandleErrorAttribute
{
   ExceptionType = typeof(SqlException),
   View = "DatabaseError",
   Order = 1
});

/* ...other error type handlers here */

filters.Add(new HandleErrorAttribute()); // default handler

請注意,HandleErrorAttribute它將僅處理 MVC 管道內部發生的錯誤(即 500 個錯誤)。

引用自:https://stackoverflow.com/questions/6596648