2009-05-01 112 views
7

这里就是我想在我Global.asax.vb做:如何在ASP.NET MVC中记录未处理的异常?

Public Class MvcApplication 
    Inherits System.Web.HttpApplication 

    Shared Sub RegisterRoutes(ByVal routes As RouteCollection) 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}") 
     routes.MapRoute(_ 
      "Error", _ 
      "error.html", _ 
      New With {.controller = "Error", _ 
         .action = "FriendlyError"} _ 
     ) 
     ... 
     'other routes go here' 
     ... 
    End Sub 

    Sub Application_Start() 
     RegisterRoutes(RouteTable.Routes) 
    End Sub 

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) 
     ... 
     'code here logs the unhandled exception and sends an email alert' 
     ... 
     Server.Transfer("http://www.example.com/error.html") 
    End Sub 

End Class 

但是Server.Transfer的失败:

Invalid path for child request 'http://www.example.com/error.html'. A virtual path is expected.

我该如何解决这个问题?或者,有什么更好的方式来做到这一点?

回答

9

我刚刚发现这个名为ELMAH斯科特Hanselman的博客here这是一个错误记录器/处理器,您可以使用而无需更改您的代码。你可能想看看它,因为它似乎与MVC很好地工作。

2

你必须specifiy虚拟路径,即相对于应用程序基础的路径(即没有路径外部应用程序),所以像: Server.Transfer的(“的error.html”) 或 服务器。转移(“/的error.html”) 或 Server.Transfer的(“〜/的error.html”)

+0

“〜/ error.html”:执行/error.html的子请求时出错。 – 2009-05-01 16:08:04

+0

“/error.html”:执行/error.html的子请求时出错。 – 2009-05-01 16:08:08

3

ELMAH是一个优秀的错误处理捕捉未处理的异常。它通过HttpModules无缝地插入到您的Web应用程序中,并提供各种通知和日志记录选项。

特点:

  • SQL,XML,SQLite的,InMemory记录
  • 电子邮件通知
  • RSS提要
  • 详细!例外的记录
  • 易于集成
  • 错误信号 - 发出一个错误的错误处理程序,而“dieing很好”,为用户

,仅供参考,SO使用ELMAH,尽管分支版本。这是最好的architectural explanationsetup tutorial

2

默认情况下,ASP.NET MVC应用程序有共享/ Error.aspx视图,从

System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo> 

继承如果你的控制器使用属性[的HandleError],所有的异常会继续冒泡直到被捕获,并且它们将在该页面上结束。

我只是增加了一个内嵌的Page_Load(在这种情况下,有效的,因为它是该行的末尾):

<script runat="server"> 
    Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs) 
    MyExceptionHandlerService.LogException("exceptionsource", this.Model.Exception) 
    End Sub 
</script> 

它后,友好“对不起......”的字样。它绝对看起来像ELMAH更强大,但为了我的需要,这已经足够了。