我想實現一個全局異常處理技術,以避免在我的控制器的每個操作上使用try/catch塊,但是我的應用程序在重寫的OnException方法之前崩潰或達到ErrorHandleAttribute。異常不被ASP.NET MVC中的ErrorHanldeAttribute或OnException方法處理5
這裏是一個簡化的測試代碼:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Test()
{
throw new Exception("Exception Test");
}
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext == null || filterContext.ExceptionHandled)
{
return;
}
var message = filterContext.Exception.Message;
filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
filterContext.ExceptionHandled = true;
}
}
和Web.Config中:
<system.web>
<customErrors mode="On" defaultRedirect="Error"/>
如果我設置的「扔」行一個破發點,並試圖訪問/首頁/測試我的應用程序將會崩潰,並且只有在這之後纔會到達OnException方法和HandleErrorAttribute。
我錯過了什麼嗎?
謝謝。
相關:[揭祕ASP.NET MVC 5錯誤頁和錯誤記錄](https://dusted.codes/demystifying-aspnet-mvc-5-error-pages-and-error-logging) – NightOwl888
@ NightOwl888偉大的文章!我試着實現那裏描述的最後四種方法(因爲前兩種方法是我原來的方法),但我沒有成功。我的應用程序在任何觸發之前都會崩潰。 – ceferrari