Monday, June 9, 2014

How to create ErrorHandling Module Using IHttpModule?

I am going to explain IHttpModule using an example here. Imagine that you don’t want to write error handling code in each and every page/class instead you want to create separate “Error Handling” module in your project without touching “Global.asax” file. You can do so by implementing “IHttpModule” interface. Following example shows you very simple code about handling error globally. I am attaching some html in beginning and End of the request. And also in between I am showing the error message occurred anywhere in the project. So here is the sample code.

Public Class ErrorHandlingModule
    Implements IHttpModule
     
    Public Sub Dispose() Implements IHttpModule.Dispose

    End Sub

    Private _ErrorMessage As String
    Public Property ErrorMessage() As String
        Get
            Return _ErrorMessage
        End Get
        Set(ByVal value As String)
            _ErrorMessage = value
        End Set
    End Property


    Public Sub Init(context As HttpApplication) Implements IHttpModule.Init

        'Adding handler for Error '
        AddHandler context.Error, _
            AddressOf Me.Application_Error

        'Adding Begin Request Handler '
        AddHandler context.BeginRequest, _
            AddressOf Me.Application_BeginRequest

        'Adding End Request Handler '
        AddHandler context.EndRequest, _
            AddressOf Me.Application_EndRequest


    End Sub

    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim application As HttpApplication = DirectCast(sender,  _
            HttpApplication)
        Dim context As HttpContext = application.Context

        context.Response.Write("<h3><font color=red>" & _
                "ErrorHandlingModule: Beginning of Request" & _
                "</font></h3><hr/><br/><br/>")

    End Sub

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        'Handling Error: This is just an example '
        'In real time, you have to log your error in database ' 
        'as well as send email to admin '
        Dim LastException As Exception = HttpContext.Current.Server.GetLastError
        If LastException IsNot Nothing Then
            If LastException.InnerException IsNot Nothing Then

                ErrorMessage = LastException.InnerException.Message

            End If
        End If

        'Clear Error after handling it '
        HttpContext.Current.Server.ClearError()

    End Sub
     
    Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim application As HttpApplication = DirectCast(sender,  _
            HttpApplication)
        Dim context As HttpContext = application.Context



        context.Response.Write(ErrorMessage + "<br/><br/><hr/><h3/><font color=red>" & _
                "ErrorHandlingModule: End of Request</font></h3>")

    End Sub

End Class


Steps:
1. Create a class “ErrorHandlingModule” in “App_Code” folder of your project
2. Implement “IHttpModule” in this class. When you press enter button at the end of “IHttpModule”, It will implement two methods “Dispose() and Init()”.
3. In Init(), I have added three handlers “Error, BeginRequest, EndRequest”.
4. To catch all requests and error, you have to subscribe those in “Init” and create methods in this class.
5. I have created three methods “Application_BeginRequest”, ”Application_Error”, ”Application_EndRequest”.
6. In “Application_Error” Method, just for example, I have assigned error message to “ErrorMessage” property. I have created this property just for that.
7. Now, just to see how it works, I have created one .aspx page and its Page_Load event, I have thrown exception as follows:

Public Class Home
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Throw New Exception("This is test ERROR")

    End Sub

End Class


When you run this page, error will be caught by our ErrorHandlingModule and you can see the result as below. You can log any error in the database as well as you can send an email to admin.

No comments:

Post a Comment

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...