The ASP.NET MVC Framework contains an attribute named HandleErrorAttribute. You can decorate a controller or an action simply by typing <HandleError> above the controller or action definition. If an unhandled exception occurs anywhere in the scope decorated with HandleErrorAttribute, MVC will display a view named "Error" to the user automatically. Typically, this view is generated for you when you create a new MVC application and is placed in the Shared folder. The HandleErrorAttribute will only work if you have customErrors turned on in your web.config. HandleErrorAttribute works great but it doesn't log. In order to add this functionality to the attribute you need to create a new class that inherits from the HandleErrorAttribute like this:
Public Class HandleErrorAndLogAttribute Inherits HandleErrorAttribute Public Overrides Sub OnException(filterContext As ExceptionContext) If Not filterContext.ExceptionHandled Then Dim MyException As Exception = filterContext.Exception ... 'Logging code goes here ... MyBase.OnException(filterContext) End If 'filterContext.Result = New ViewResult With {.ViewName = "Error"} End Sub End Class
Now, if you want to use your new attribute, you would just type <HandleErrorAndLog>. You can globally apply this attribute to everything in your application by editing the FilterConfig.vb file like this:
Public Module FilterConfig Public Sub RegisterGlobalFilters(ByVal filters As GlobalFilterCollection) 'filters.Add(New HandleErrorAttribute()) filters.Add(New HandleErrorAndLogAttribute()) End Sub End Module
Apparently, there are certain exceptions that this attribute does not handle such as HTTP exceptions that occur outside of the MVC context. To ensure these errors are handled, you should also log errors in the MvcApplication_Error event of the Global.asax.vb file. Be sure to set the defaultRedirect attribute of the customErrors node in the web.config file to the Error View. You will need to create an action method that will display the Error view when it is redirected in this way..
No comments:
Post a Comment