views:

2604

answers:

2

I'm creating an ASP.NET MVC application. I need to handle exceptions in two places.

Global.asax.vb file:

Public Class MvcApplication
    Inherits System.Web.HttpApplication
    ...
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        LogException(HttpContext.Current.Server.GetLastError(), Request)
    End Sub
    Shared Sub LogException(ByVal ex As Exception, ByRef r As System.Web.HttpRequest)
        ...
    End Sub
End Class

Views\Shared\Error.aspx file:

<%@ Page Language="VB" Inherits="System.Web.Mvc.ViewPage(Of System.Web.Mvc.HandleErrorInfo)" %>
<script runat="server">
    Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs)
        MvcApplication.LogException(Model.Exception, Request)
    End Sub
</script>
...

But I get this error:

C:\inetpub\example.com\Views\Shared\Error.aspx(5): error BC30451: Name 'MvcApplication' is not declared.

Where should I define my LogException() function so that it is accessible from both the Global.asax.vb file and the Error.aspx file? Where is the most MVC-ish?

+2  A: 

The most MVC-ish way would be to use ActionFilters to handle (log) exceptions.

Check out this for example:

Logging with ASP.NET MVC Action Filters

User
+1 one from me, however, what if an error occurs in your Application_Start? We have quite a log of Autofac and NHibernate set up in _start and if anything goes wrong and throws an error, an ActionFilter will never catch that error. Careful!
Perhentian
That example seems to be about logging actions, rather than logging exceptions
codeulike
+3  A: 

You may want to try an module called ELMAH. Scott Hanselman says "ELMAH is Tivo for your ASP.NET Errors". I've am currently using it for logging errors in my ASP .NET + MVC applications and it works like a charm. Setup was easy because all that is required is adding lines to the web.config. You can even restrict who has access to view the error logs.

http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx

SideFX