+ Reply to Thread
Results 1 to 5 of 5

Thread: .Net Global Error Handling

  1. #1
    The Barnfather jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead's Avatar
    Join Date
    Mar 2008
    Location
    Reston, VA
    Posts
    4,547
    Blog Entries
    9
    Real Name
    Jason
    Rep Power
    22

    .Net Global Error Handling

    This is an example of one method to trap errors in a .Net application. This method uses the Application_Error event in the Global.ASAX and the customErrors node in the web.config file to send the user to 'friendly' error page. The actual error details and other information are sent to the email provided in the Application_Error event.

    First, the Global.asax code:
    Code:
    <%@ Application Language="VB" %>
    <%@ Import Namespace="System.Diagnostics" %>
    <script runat="server">
        Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs on application startup
        End Sub
        
        Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs on application shutdown
        End Sub
            
        Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
            '//Get reference to the source of the exception chain
            Dim ex As Exception = Server.GetLastError().GetBaseException()
            Dim messageBody As New StringBuilder
            Dim errMessage As String = ex.Message.ToString()
            Dim i As Integer = 0
            
            '//Build message body
            With messageBody
                .Append("<p><b>" & Server.HtmlEncode(Request.Url.ToString) & "</b><ul>")
                For i = 1 To Request.Params.Count
                    If Not Request.Params.Keys(i - 1) = "AUTH_PASSWORD" Then
                        .Append("<li>" & Server.HtmlEncode(Request.Params.Keys(i - 1).ToString) & _
                                " = <u>" + Server.HtmlEncode(Request.Params.Item(i - 1).ToString) + "</u></li>")
                    End If
                Next
                .Append("</ul></p>")
                
                i = 0
                Do While (Not ex Is Nothing) And i < 10
                    .Append("<hr>" & htmlException(ex))
                    ex = ex.InnerException
                    i += 1
                Loop
            End With
            
            '//Email details of the error to support staff
            Dim message As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage
            With message
                .From = New System.Net.Mail.MailAddress(someemail@somedomain.com)
                .To.Add(New System.Net.Mail.MailAddress(someotheremail@somedomain.com))
                .Subject = "Application Error - " & errMessage.ToString
                .IsBodyHtml = True
                .Body = messageBody.ToString()
            End With        
            
            Dim client As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient()
            client.Send(message)
        End Sub
        
        Function htmlException(ByVal ex As Exception) As String
            Dim str As New StringBuilder
            With str
                .Append("<p><b>Message:</b><br />" & Server.HtmlEncode(ex.Message.ToString) & "</p>")
                .Append("<p><b>Source:</b><br />" & Server.HtmlEncode(ex.Source.ToString) & "</p>")
                .Append("<p><b>Target Site:</b><br />" & Server.HtmlEncode(ex.TargetSite.Name.ToString) & "</p>")
                .Append("<p><b>Stack Trace:</b><br />" & Replace(Server.HtmlEncode(ex.StackTrace.ToString), vbCrLf, "<br />") & "</p>")
            End With
            Return str.ToString()
        End Function
        Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs when a new session is started
        End Sub
        Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs when a session ends. 
            ' Note: The Session_End event is raised only when the sessionstate mode
            ' is set to InProc in the Web.config file. If session mode is set to StateServer 
            ' or SQLServer, the event is not raised.
        End Sub
           
    </script>
    
    Then, in the web.config:
    Code:
    <customErrors mode="RemoteOnly" defaultRedirect="~/Error.aspx">
     <error statusCode="404" redirect="~/Error.aspx?code=404"/>
     <error statusCode="403" redirect="~/Error.aspx?code=403"/>
    </customErrors>
    
    This allows you to determine which page the user gets sent to. Notice the <error statusCode /> node. You can leave this blank or put as many statusCodes as you need here. Also, note the mode attribute. I like to use RemoteOnly as it allows anyone who is physically at the server to see the actual error message, but sends anyone who is logged in remotely to the error page. The other options are "On" and "Off".

    On Error.aspx, you can put a generic error message, or use a Select Case based on the status code passed in the 'code' querystring value, to determine what error message to display to the user.

    This is just one method to handle errors in your application.
    jmurrayhead
    If you agree, give me rep.
    If you like it here...throw us a few bones to help support us.


  2. #2
    Administrator richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich's Avatar
    Join Date
    Mar 2008
    Location
    Somewhere only we know...
    Posts
    3,207
    Blog Entries
    14
    Real Name
    Rich
    Rep Power
    14

    Is it possible to show an error message on the page rather than redirecting to another page and dependant on the action that was being taken at the time?

    E.g. if it was whilst loading a specific item on the page, like a dropdownlist from a List(of ) object, or if it was whilst trying to update a particular db entry.

    Can this be used in conjunction with a Try..Catch block, so the try..catch outputs a message to the screen whilst the Application_Error Sub sends an email detailing the error?

  3. #3
    The Barnfather jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead has much to be proud of jmurrayhead's Avatar
    Join Date
    Mar 2008
    Location
    Reston, VA
    Posts
    4,547
    Blog Entries
    9
    Real Name
    Jason
    Rep Power
    22

    You can capture the errors using Try...Catch and then Rethrow the error so that the Application_Error event is fired. You would turn off customErrors in the web.config for this to work.
    jmurrayhead
    If you agree, give me rep.
    If you like it here...throw us a few bones to help support us.


  4. #4
    Administrator richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich is a splendid one to behold richyrich's Avatar
    Join Date
    Mar 2008
    Location
    Somewhere only we know...
    Posts
    3,207
    Blog Entries
    14
    Real Name
    Rich
    Rep Power
    14

    Quote Originally Posted by jmurrayhead View Post
    You can capture the errors using Try...Catch and then Rethrow the error so that the Application_Error event is fired. You would turn off customErrors in the web.config for this to work.
    So if I had a Try...Catch block in a DAL function then I could use:-
    Code:
    Catch ex As Exception
    myObj.err = ex.toString
    Throw New Exception
    
    And it would still return to my page so I could render a message to the screen on the same page? and then Application_Error sub would send me the error email?

  5. #5
    Wolfmaster Wolffy is a splendid one to behold Wolffy is a splendid one to behold Wolffy is a splendid one to behold Wolffy is a splendid one to behold Wolffy is a splendid one to behold Wolffy is a splendid one to behold Wolffy is a splendid one to behold Wolffy is a splendid one to behold Wolffy's Avatar
    Join Date
    Mar 2008
    Location
    Peoria, IL
    Posts
    2,386
    Blog Entries
    5
    Real Name
    Wolff
    Rep Power
    15

    To rethrow the exception, I believe it's
    Code:
    Catch ex As Exception
    'Do Whatever
    Throw
    
    Wolffy
    .-- ----- ..-. ..-. -.--
    Opinions expressed are my own and do not necessity reflect those of any sane person. Any code provided is intended to be an example and is provided AS IS. Void where prohibited by law. Not valid in California. Your mileage may vary.

+ Reply to Thread

Similar Threads

  1. Global Error Class
    By richyrich in forum .NET Development
    Replies: 14
    Last Post: March 23rd, 2009, 11:32 AM
  2. Handling Delimited Strings in T-SQL
    By jmurrayhead in forum Microsoft SQL Server
    Replies: 5
    Last Post: January 9th, 2009, 12:54 PM
  3. Help with handling sql insert error
    By Rebelle in forum ASP Development
    Replies: 11
    Last Post: August 29th, 2008, 02:20 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

SEO by vBSEO