捕获 MVC 3.0 应用程序中抛出的所有错误的干净方法?

发布于 2024-12-24 17:20:47 字数 241 浏览 4 评论 0原文

我正在构建一个 MVC 3.0 电子商务网站。我想避免在我的代码中粘贴 try-catch 块。

问题非常简单 - 捕获我的网站上抛出的所有错误的好策略是什么?我想了解所有这些……这样我就可以在网站上线后努力将计数降至 0。我计划将每个错误写入记录器并通过电子邮件发送。

我已经阅读了一些有关在 global.asax 文件中捕获它的内容...但我也读到它并没有获取所有内容。

有人有任何建议或能给我指出一个好的方向吗?

I'm building an MVC 3.0 ecommerce site. I want to avoid sticking try-catch blocks all over my code.

Question is pretty simple - What is a good strategy for capturing all errors that are thrown on my website? I want to know about all of them... so I can work on bringing that count to 0 once the site goes live. I plan on writing each error to a logger and also to email it.

I've done some reading about capturing it in the global.asax file... but i've also read that it doesn't get ALL of them.

Anyone have any suggestions or can point me in a good direction?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

2024-12-31 17:20:47

解决该问题的 MVC 方法是过滤器。如果您已经使用 MVC3,那么全局过滤器适合您。有一种特殊类型的过滤器用于处理错误:HandleError 过滤器。 这篇文章描述了它的大部分使用方法。

您可以实现自己的过滤器并控制未处理异常的各个方面,例如:

public class HandleExceptionsAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var expception = filterContext.Exception;

        // custom code here..
    }
}

最后,如果您希望存储和记录所有未处理异常,ELMAH 即 ELMAH.MVC 是最好的选择。使用 NuGet 包 安装它,配置它,所有数据都可以通过以下链接访问:

http://yourapp/admin/elmah/

我的建议是不要在 Global.asax.cs 中使用类似 Application_Error 的内容。

The MVC way of solving that problem are filters. If you are on MVC3 already, global filters are for you. There is special type of filter for handing errors: the HandleError filter. This article describes much of using it.

You might implement you own filter and control every aspect of of unhandled exceptions, e.g.:

public class HandleExceptionsAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var expception = filterContext.Exception;

        // custom code here..
    }
}

Finally, if you want to have all unhandled exceptions to be stored and logged, ELMAH i.e. ELMAH.MVC is the best choice. Install it by using the NuGet package, configure it and all data will be accessed from a link such as:

http://yourapp/admin/elmah/

My suggestion is to not use anything like Application_Error in Global.asax.cs.

往日 2024-12-31 17:20:47

您可以在 Global.asax 中处理任何抛出的异常。

protected void Application_Error(object sender, EventArgs e) 
{
  Exception exception = Server.GetLastError();
  // global handling code goes here

  Server.ClearError();
}

You can handle any thrown Exception in the Global.asax.

protected void Application_Error(object sender, EventArgs e) 
{
  Exception exception = Server.GetLastError();
  // global handling code goes here

  Server.ClearError();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文