【发布时间】:2016-10-15 06:17:18
【问题描述】:
我正在尝试实现一种全局异常处理技术,以避免在我的控制器的每个操作上使用 try/catch 块,但我的应用程序在覆盖的 OnException 方法或 ErrorHandleAttribute 到达之前崩溃。
这是一个简化的测试代码:
[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"/>
如果我在“throw”行设置断点并尝试访问 /Home/Test,我的应用程序将崩溃,并且只有在此之后才会到达 OnException 方法和 HandleErrorAttribute。
我错过了什么吗?
谢谢。
【问题讨论】:
-
@NightOwl888 好文章!我尝试实现那里描述的最后四种方法(因为前两种是我最初拥有的方法)但我没有成功。我的应用程序将在它们中的任何一个被触发之前崩溃。
标签: asp.net asp.net-mvc exception error-handling exception-handling