asp.net-mvc-3onerrorhandleerror

ASP.NET MVC Override HandleError causes View to not render


In my app I'm using "HandleError" whereby if an error happens, my "Error.vbhtml" view renders. This is working great, except now I want to also log the error. I've built a custom HandleError Class, Inherited the HandleErrorAttribute, and Overridden the OnException method.

Now my error gets logged, but the Error.vbhtml view doesn't get rendered... what praytell am I messing?

Imports System.Web.Mvc

Namespace Mvc.Attributes
    Public Class HandleError : Inherits System.Web.Mvc.HandleErrorAttribute
        Private ExceptionService As Domain.IExceptionService
        Public Sub New()
            ExceptionService = New Domain.ExceptionService(New Domain.ExceptionRepository)
        End Sub

        Public Overrides Sub OnException(ByVal exceptionContext As ExceptionContext)
            ''# Log the exception if it has not been handled elsewhere
            If Not exceptionContext.ExceptionHandled Then
                ExceptionService.AddException(exceptionContext.Exception)
                ExceptionService.SubmitChanges()
                ''# Signal to the system that we've handled the exception
                exceptionContext.ExceptionHandled = True
            End If
        End Sub
    End Class
End Namespace

Solution

  • I just took a look at the source code of the HandleError method at Codeplex. I scooped some of the code from there

            Dim controllerName As String = DirectCast(filterContext.RouteData.Values("controller"), String)
            Dim actionName As String = DirectCast(filterContext.RouteData.Values("action"), String)
            Dim model As New HandleErrorInfo(filterContext.Exception, controllerName, actionName)
            filterContext.Result = New ViewResult() With { _
             .ViewName = View, _
             .MasterName = Master, _
             .ViewData = New ViewDataDictionary(Of HandleErrorInfo)(model), _
             .TempData = filterContext.Controller.TempData _
            }
            filterContext.ExceptionHandled = True
            filterContext.HttpContext.Response.Clear()
            filterContext.HttpContext.Response.StatusCode = 500
    
            ''# Certain versions of IIS will sometimes use their own error page when
            ''# they detect a server error. Setting this property indicates that we
            ''# want it to try to render ASP.NET MVC's error page instead.
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = True
    

    This appears to work