PBMining

Searching...
Sunday, July 1, 2012

Creating Custom Exception Filter in MVC 3

10:20 AM

IExceptionFilter interface in MVC provide abstract method that we can override for our custom logic to handle exception and also we can derived our class from FilterAttribute so it can be use as a attribute on controllers or actions.

MVC provide HandleError attribute for handle any exception fire by controller, action or by any other attributes.In our custom exception filter we add more benefit for redirecting to a action or route when exception occur.

Here we have created three properties for storing routing values and exception.


    Public Class CustomException
        Inherits FilterAttribute
        Implements IExceptionFilter
        

        Private _exceptionType As Type = GetType(Exception)
        Public Property Action As String
        Public Property Controller As String
        
        Public Property ExceptionType As Type
            Get
                Return _exceptionType
            End Get
            Set(value As Type)
                If Not GetType(Exception).IsAssignableFrom(value) Then
                    Throw New ArgumentException("Exception Type not supported")
                End If
            End Set
        End Property

         End Class
        

In OnException method of our implementation we just check for prerequisites for parameters. and get the currentController and Action from RouteData of filterContext that we use for creating instance of HandleErrorInfo and storing it in TempData so we can display or log the error information.

        Public Sub OnException(filterContext As System.Web.Mvc.ExceptionContext) Implements System.Web.Mvc.IExceptionFilter.OnException
        
            If String.IsNullOrEmpty(Action) Or String.IsNullOrEmpty(Controller) Then
                Throw New ArgumentException("values for action or controller not supplied")
            End If

            'if action is child action
            If filterContext.IsChildAction Then
                Return
            End If

            'if exception is handled by some other filter or custom error mode in web.config is not enabled
            If filterContext.ExceptionHandled or Not filterContext.HttpContext.IsCustomErrorEnabled Then
                Return
            End If
            Dim exception As Exception = filterContext.Exception

            'if current exception is any httpexception then just return
            If Not (New HttpException(Nothing, exception).GetHttpCode = 500) Then
                Return
            End If

            'exception that is fire is instance of type that is passed as argument
            If Not ExceptionType.IsInstanceOfType(exception) Then
                Return
            End If

            Dim currentController As String = filterContext.RouteData.Values("Controller")
            Dim currrentAction As String = filterContext.RouteData.Values("Action")

            Dim errorInfo As New HandleErrorInfo(exception, currentController, currrentAction)
            filterContext.Controller.TempData("Model") = errorInfo

            filterContext.Result = New RedirectToRouteResult(New RouteValueDictionary(New With {.action = Action, .controller = Controller}))

            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

        End Sub
        
   
    

Next thing is main function of our custom implementation to redirect to action,we just set result property of filterContext to RedirectToRouteResult and pass action and controller as parameters.

ExceptionHandled property of filterContext is set true so other filter can know that exception is handled. Response.StatusCode = 500 that says this exception is not a standard httpException.


0 comments:

Post a Comment

Write your review about this post.