Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I log unhandled exceptions in ASP.NET MVC?

Here's what I'm trying to do in my Global.asax.vb:

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

But that Server.Transfer fails:

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

How do I fix this? Or, what's a better way for me to do this?

like image 720
Zack Peterson Avatar asked May 01 '09 15:05

Zack Peterson


People also ask

How do you find the unhandled exception?

If your application has unhandled exceptions, that may be logged in the Windows Event Viewer under the category of “Application”. This can be helpful if you can't figure out why your application suddenly crashes. Windows Event Viewer may log 2 different entries for the same exception.

How will you implement logging in MVC application?

Add log4net in config file config and enter the following details. Add a class Log. cs in the Utilities folder. Now, in the constructor of this class, instantiate logs for monitoring and debugger loggers.


2 Answers

I just found this on Scott Hanselman's blog here called ELMAH which is an Error Logger/Handler that you can use without having to change your code. You might want to look into it, since it seems to work nicely with MVC.

like image 52
Joseph Avatar answered Sep 27 '22 21:09

Joseph


ELMAH is an excellent error handler for catching unhandled exceptions. It plugs seamlessly into your web application via HttpModules and has various options for notification and logging.

Features:

  • SQL, XML, SQLite, InMemory Logging
  • Email notification
  • RSS feed
  • Detailed! logging of exceptions
  • Easy integration
  • Error Signalling - signal the error handler of an error while "dieing nicely" for the user

And FYI, SO uses ELMAH, albeit a forked version. This is the best architectural explanation and setup tutorial

like image 32
Gavin Miller Avatar answered Sep 27 '22 22:09

Gavin Miller