How do I log unhandled exceptions in ASP.NET MVC?
-
03-07-2019 - |
Question
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?
OTHER TIPS
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
You have to specifiy a virtual path, i.e. a path relative to the application base (i.e. no paths external to the app), so something like: Server.Transfer("error.html") or Server.Transfer("/error.html") or Server.Transfer("~/error.html")
By default, ASP.NET MVC applications have a view Shared/Error.aspx, inheriting from
System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>
If your controller uses the attribute [HandleError], all exceptions will continue to bubble until caught, and they will end up on that page.
I simply added an inline Page_Load (valid in this case since it's the end of the line):
<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>
After it, the friendly "Sorry..." message. It definitely looks like ELMAH is more robust, but for my needs, this was sufficient.