Click here to Skip to main content
Click here to Skip to main content

User Friendly ASP.NET Exception Handling

By , 20 Dec 2004
 

Sample Image - ASPNETExceptionHandling.gif

Introduction

This article is a follow-up to my previous CodeProject article, User Friendly Exception Handling, which covered global exception handling for console and WinForms apps. As I mentioned in that article:

This leaves out one large class of .NET applications: web apps. I've experimented with this, and I do not believe it is desirable to handle web exceptions using the exact same classes that you use to handle Console and WinForms exceptions. They have different needs. I do have a variant of this class I use in server-side Web Services and ASP.NET applications, but it's significantly different.

This article covers a similar global exception handling technique for ASP.NET applications and Web Services. I won't go over any of the background on exceptions, as that was covered in the introduction to the previous article. Let's jump right into the implementation.

Unhandled Exceptions in ASP.NET Websites

There are two approaches you can use when you set out to design a global exception handler in ASP.NET.

The first method is the most straightforward: using the Application_Error event in the Global.asax file. This event fires whenever an unhandled exception occurs in an ASP.NET application. So, we can hook up our shared AspUnhandledException class there:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    Dim ueh As New ASPUnhandledException.Handler
    ueh.HandleException(Server.GetLastError.GetBaseException())
End Sub

Most ASP.NET developers are familiar with global.asax, so this method is easy to explain. It's also the method I used in the previous version of this article. While you can still do this, there is a better way.

And that second, better way is to hook into the ASP.NET HTTP pipeline by implementing IHttpModule:

Public Class UehHttpModule
    Implements IHttpModule
    Public Sub Init(ByVal Application As System.Web.HttpApplication) 
             Implements System.Web.IHttpModule.Init
        AddHandler Application.Error, AddressOf OnError
    End Sub
    Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
    End Sub
    Protected Overridable Sub OnError(ByVal sender As Object, 
           ByVal args As EventArgs)
        Dim app As HttpApplication = CType(sender, HttpApplication)
        Dim ueh As New ASPUnhandledException.Handler
        ueh.Handle(app.Server.GetLastError)
    End Sub
End Class

This is functionally identical to the first method, with one key difference: you can now implement global exception handling without recompiling the ASP.NET application! This means you can retrofit unhandled exception handling to any ASP.NET website with ease -- just copy the ASPUnhandledException.dll file to the \bin folder, then make a minor edit to the Web.config:

<system.web>
  <httpModules>
  <add name="UehHttpModule"                 
       type="ASPUnhandledException.UehHttpModule, ASPUnhandledException" />  
  </httpModules>
</system.web>

And off you go. Isn't that cool?

Unhandled Exceptions in ASP.NET Web Services

Unfortunately, neither of these methods will work for a .NET Web Service. Application_Error will never fire, and the HTTP pipeline is bypassed in favor of the SOAP pipeline. To globally handle exceptions for a web service, we have to implement a SoapExtension:

Public Class UehSoapExtension
    Inherits SoapExtension
    
    Private _OldStream As Stream
    Private _NewStream As Stream
    
    Public Overloads Overrides Function GetInitializer( _
    ByVal serviceType As System.Type) As Object
        Return Nothing
    End Function
    
    Public Overloads Overrides Function GetInitializer( _
    ByVal methodInfo As System.Web.Services.Protocols.LogicalMethodInfo,  _
    ByVal attribute As System.Web.Services.Protocols.SoapExtensionAttribute) 
    As Object
        Return Nothing
    End Function
    
    Public Overrides Sub Initialize(ByVal initializer As Object)
    End Sub
    
    Public Overrides Function ChainStream(ByVal stream As Stream) As Stream
        _OldStream = stream
        _NewStream =  New MemoryStream 
        Return _NewStream 
    End Function
    
    Private Sub Copy(ByVal fromStream As Stream, ByVal toStream As Stream)
        Dim sr As New StreamReader(fromStream)
        Dim sw As New StreamWriter(toStream)
        sw.Write(sr.ReadToEnd())
        sw.Flush()
    End Sub
    
    Public Overrides Sub ProcessMessage(ByVal message _
    As System.Web.Services.Protocols.SoapMessage)
        Select Case message.Stage
            Case SoapMessageStage.BeforeDeserialize
                Copy(_OldStream, _NewStream)
                _NewStream.Position = 0
            Case SoapMessageStage.AfterSerialize
                If Not message.Exception Is Nothing Then
                    Dim ueh As New Handler
                    Dim strDetailNode As String
                    '-- handle our exception, and get the SOAP <detail> string
                    strDetailNode = ueh.HandleWebServiceException(message)
                    '-- read the entire SOAP message stream into a string
                    _NewStream.Position = 0                    
                    Dim tr As TextReader = New StreamReader(_NewStream)
                    '-- insert our exception details into the string
                    Dim s As String = tr.ReadToEnd
                    s = s.Replace("<detail />", strDetailNode)
                    '-- overwrite the stream with our modified string
                    _NewStream = New MemoryStream
                    Dim tw As TextWriter = New StreamWriter(_NewStream)
                    tw.Write(s)
                    tw.Flush()
                End If
                _NewStream.Position = 0
                Copy(_NewStream, _OldStream)
        End Select
    End Sub
    
End Class

The SoapExtension is a little more complicated than our HttpModule, because we have to modify the SOAP message to include the detailed exception information. I'll cover this in more detail later. All you need to do to get this working in your Web Service is copy the ASPUnhandledException.dll file to the \bin folder, then make a minor edit to the Web.config:

<webServices>
  <soapExtensionTypes>
    <add type="ASPUnhandledException.UehSoapExtension, ASPUnhandledException"
         priority="1" group="0" />
  </soapExtensionTypes>
</webServices>

Configuring AspUnhandledException

The AspUnhandledException class is configured through a custom configuration section named <UnhandledException> in Web.config. The class will work without any configuration, but all you'll get by default is a plain text log file in the root of your website. I suggest adding the following to your Web.config as a practical minimum:

<configSections>    
  <section name="UnhandledException" 
     type="System.Configuration.NameValueSectionHandler, System, 
           Version=1.0.5000.0, Culture=neutral, 
           PublicKeyToken=b77a5c561934e089" />
</configSections>

<UnhandledException>
  <add key="ContactInfo" value="Ima Testguy at 123-555-1212" />
  <add key="EmailTo" value="me@mydomain.com" />
  <add key="SmtpDefaultDomain" value="mydomain.com" />
  <add key="SmtpServer" value="mail.mydomain.com" />
</UnhandledException>

This is the complete list of configuration settings:

Key Default Description
EmailTo none semicolon delimited list of email addresses to send exception notifications to
EmailFrom server@domain.com override for the from address provided in exception emails. Optional.
IgnoreDebug True do not handle any exceptions when the debugger is attached, or if the originating exception host is localhost. If you want to debug the error handler, be sure to set this to False.
IgnoreRegex "" If this regular expression pattern evaluates to true against any part of the exception string, ignore this exception.
LogToEventLog False write an unhandled exception event to the Event Log
LogToEmail True send an unhandled exception email to the addresses in EmailTo
LogToFile True write an unhandled exception entry to a plain text log file
LogToUI True automatically display a customized unhandled exception HTML page
PathLogFile "" path to the plain text exception log file. Can be fully qualified or relative, with or without a filename. If it is relative, assumed to be relative to the root folder of the website. If no path provided, the default filename is used at the root of the website.
AppName none used on default error HTML page to replace any instances of "(app)" in strings
ContactInfo none used on default error HTML page to replace any instances of "(contact)" in strings
PageTitle (see screenshot) title of default error HTML page
PageHeader (see screenshot) header of default error HTML page
WhatHappened (see screenshot) Text to display in default error HTML web page under the "What happened:" heading
HowUserAffected (see screenshot) Text to display in default error HTML web page under the "How this will affect you:" heading
WhatUserCanDo (see screenshot) Text to display in default error HTML web page under the "What you can do about it:" heading

Once you've copied the .dll file to the /bin folder, and checked your Web.config settings, everything else is automatic from this point on.

ASPUnhandledException with ASP.NET websites

Okay, so now that you've hooked this up, what do you get for your troubles? Well, whenever an unhandled exception occurs in your website or web service, one or more of the following will automatically happen:

  1. A user friendly webpage is displayed to the user
  2. An email notification is sent to the address(es) of your choice
  3. A plaintext log file is written to the path and filename of your choice
  4. An entry is written to the event log

All of these options will contain the same detailed diagnostic information about the exception, which is generated by ExceptionToString. I'll now cover each of these events in more detail.

If LogToUI is left at the default of True, we automatically generate a user-friendly web page based on the GUI design laid out by Alan Cooper in his book About Face: The Essentials of User Interface Design, in the chapter titled The End of Errors. Note that if you turn off LogToUI, you'll revert to the default ASP.NET "yellow screen of death" page.

screenshot of custom unhandled exception web page

If LogToEmail is left at the default of True, your unhandled exceptions will automatically be emailed via the bundled managed SMTP class SimpleMail. This class requires valid SMTP settings in the Web.config custom configuration section <UnhandledException>. The complete list of configuration settings is:

Key Default Description
SmtpDefaultDomain none Default email domain name used for emails that don't provide a domain
SmtpServer none SMTP email server used to send emails
SmtpPort 25 SMTP port used to send emails
SmtpAuthUser none If outgoing mail authentication is enabled, user name used for authentication
SmtpAuthPassword none If outgoing mail authentication is enabled, password used for authentication

The exception email contains:

  • User and machine identification
  • Application information
  • Exception summary
  • Custom stack trace
  • All ASP.NET collection contents

screenshot of automatic exception email

If LogToFile option is left at the default of True, unhandled exceptions will be written to a plain text log file in the root of your website, named UnhandledExceptionLog.txt. If you require a different path, use the PathLogFile setting to specify either a relative or absolute path, with or without a filename. If the path is relative, it is assumed to be relative to the root of the current website. Whatever path you specify must have ASP.NET write permissions, otherwise the logging will silently fail.

If LogToEventLog is enabled, you will get this same detailed exception information in the Application Event Log. Note that you must grant the ASP.NET process account permission to write to the registry for this to function. I don't frequently do this in my apps, which is why I defaulted it to False, but it does work!

ASPUnhandledException with ASP.NET Web Services

In my previous article, I bemoaned the lack of good global error handling provisions for ASP.NET Web Services. Well, not any more. Using a custom SoapExtension, it's easy! And generally, it works the same as in ASP.NET. There are, however, a few important differences you should be aware of:

  1. Using a SOAPExtension means we only catch SOAP unhandled exceptions-- you will not be able to test unhandled exceptions using the web browser interface! Please bear this in mind! I included a demo SOAP console application in the solution for this very reason.
  2. SOAP clients don't have a browser interface, so the LogToUI option is not available for Web Services, and is ignored in this case.
  3. The SoapException is a bit different than your typical .NET Exception, it contains a special XML <detail> element for details on the server part of the exception.

The only tricky part left is inserting the rich exception information we've come to expect from our ASP.NET exceptions into the SOAP message. By default, the <detail> element is very sparse, so almost nothing is communicated from the server to the client:

<soap:Fault>
  <faultcode>soap:Server</faultcode>
  <faultstring>SoapException</faultstring>
  <detail/>
</soap:Fault>

Hard to diagnose this exception with so little information. That's where the Handler.HandleWebServiceException comes in. We call this method from the SoapExtension, and it generates a much better <detail> element for us:

Public Function HandleWebServiceException(ByVal sm As _
              System.Web.Services.Protocols.SoapMessage) As String
    _blnLogToUI = False
    HandleException(sm.Exception)
    
    Dim doc As New Xml.XmlDocument
    Dim DetailNode As Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _
        SoapException.DetailElementName.Name, _
        SoapException.DetailElementName.Namespace)
    
    Dim TypeNode As Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _
        "ExceptionType", _
        SoapException.DetailElementName.Namespace)
    TypeNode.InnerText = _strExceptionType
    DetailNode.AppendChild(TypeNode)
    
    Dim MessageNode As Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _
        "ExceptionMessage", _
        SoapException.DetailElementName.Namespace)
    MessageNode.InnerText = sm.Exception.Message
    DetailNode.AppendChild(MessageNode)
    
    Dim InfoNode As Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _
        "ExceptionInfo", _
        SoapException.DetailElementName.Namespace)
    InfoNode.InnerText = _strException
    DetailNode.AppendChild(InfoNode)
    
    Return DetailNode.OuterXml.ToString()
End Function

The string returned from this method is used to modify the SOAP message "in flight", and we get a much better <detail> node:

<soap:Fault>
  <faultcode>soap:Server</faultcode>
  <faultstring>Server was unable to process request. -->

I trimmed many of the <ExceptionInfo> lines, but it's the same rich diagnostic information you've seen before.

Conclusion

One final observation on Unhandled Exceptions, before we close our discussion. You must avoid exceptions in the Unhandled Exception Handler. This is a special case handler, the "handler of last resort", and exceptions in this code are extremely bad form. They can cause the code to terminate with no warning whatsoever, as if you put in an arbitrary Return right smack dab in the middle of your function. I have taken great precautions in my handler to avoid exceptions, but be warned.

I've used this class on about a dozen different websites and web services so far, with excellent results. There are many more details and comments in the source code provided at the top of the article, so check it out. Please don't hesitate to provide feedback, good or bad!

I hope you enjoyed this article. If you did, you may also like my other articles as well.

History

  • Saturday, August 21, 2004 - Published
  • Monday, September 27, 2004 - Updated demo code
    • Fixed problem where inner exceptions were discarded in global.asax.
    • Added code to ignore the outermost ASP.NET exception (it's the same every time).
    • Removed ConfigurationException that was previously thrown when Company and Product were not populated in AssemblyInfo.
  • Sunday, October 17, 2004 - Version 2.0
    • Added SoapExtension and HttpHandler.
    • Many improvements to base Handler class (and a few bug fixes).
    • Rebuilt article and demo solution.
  • Saturday, December 18, 2004 - Version 2.1
    • Uses a separate custom <UnhandledException> .config file section.
    • added .config values EmailFrom, PageTitle and PageHeader.
    • viewstate is sent as a plaintext email attachment (when present).
    • smarter, more concise formatting of ASP.NET collections.
    • added ASP.NET Session, Cache, and Application collection summary.
    • more feedback provided in the LogToUi page when there is a failure to log via email, file, or event log.
    • the "More Details:" section of the HTML error page is now an expander button to simplify the output for casual users.
    • converted to VB.NET 2005 style XML comments.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

wumpus1
Web Developer
United States United States
Member
My name is Jeff Atwood. I live in Berkeley, CA with my wife, two cats, and far more computers than I care to mention. My first computer was the Texas Instruments TI-99/4a. I've been a Microsoft Windows developer since 1992; primarily in VB. I am particularly interested in best practices and human factors in software development, as represented in my recommended developer reading list. I also have a coding and human factors related blog at www.codinghorror.com.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberFarhan Ghumra17 Jun '12 - 23:08 
Excellent
QuestionC# VersionmemberJohn M. Baughman6 Jun '12 - 17:20 
(Yeah, it's a copy of my own comment...)
 
And FINALLY: http://github.com/johnmbaughman/UnhandledException[^]
QuestionCan handle exeption in webservice via HttpPost ?memberphamtrungthanh9 Jan '12 - 21:14 
Thanks for your solution. It work perfectly when handle exception in web service via SOAP envelope.
Unfortunately, when I try to call my Web service via HttpPost, the exception show to every one, include stacktrace, etc ...
So, is the any solution or tips for handle exception in Web service called via HttpPost ?
QuestionRE: Totally don't workmemberadriankohws24 Nov '11 - 20:03 
Hi, first of all, unzip the whole of your 4 projects couldn't get me to see the mentioned dll file.
Unzip your project, doesn't work. According to readme, unzip the root$ into local host, I check the Internet saying localhost is not a folder, so I don't know where to unzip to.....
 
Why not you just allow user to download your "DLL" and I think the rest, just setting up the webconfig is easy, other than giving everyone the whole beautiful thing but it doesn't work.
GeneralMy vote of 1membernaresh@hits4 Nov '11 - 2:49 
no
Suggestion404 and Googlememberezq67226 Jul '11 - 1:32 
This code is awesome and I have been using it in my project for some time. A short while ago I changed the structure of the site and ever since I have been receiving exceptions as a result of google crawling the site and requesting non-existent pages. Google never learns that these pages are long gone because the Exception handling code always returns a result code of 200.
 
Using the simple mod below, the code now passes on any HTTP status codes along with the friendly Exception page.
 
New Global Variable:
Private _intStatusCode As Integer = 200
 
Addition to HandleException():
If TypeOf ex Is HttpException Then
  _intStatusCode = CType(ex, HttpException).GetHttpCode()
End If
 
Addition to ExceptionToPage():
HttpContext.Current.Response.StatusCode = _intStatusCode
 
Using this new code Google will quickly learn that the pages are not there and will soon remove them from its index.
 
Stuart
GeneralC# VersionmemberJohn M. Baughman11 Feb '11 - 4:12 
I have the entire project ported over to C#...
 
ASP.NET Unhandled Exception Handler[ASP.NET Unhandled Exception Handler]
 
See the article for more. If I get some kind of response, I'll find a host for the Zip file.
 
-John
GeneralRe: C# VersionmemberJohn M. Baughman9 Nov '11 - 19:56 
Sorry to all who asked for the C# version, I'm working on getting it uploaded for you.
GeneralRe: C# VersionmemberJohn M. Baughman6 Jun '12 - 17:18 
And FINALLY: http://github.com/johnmbaughman/UnhandledException[^]
GeneralPiece of demo is missingmemberMember 358175318 Jun '10 - 8:48 
Hi Jeff,
 
It looks like some of the demo is missing from the zip file. The solution tree in VS 2005 shows four nodes.
 
1. ASPUnhandledException
2. WebServiceTestConsoleApplication
3. UnhandledExceptionWeb
4. UnhandledExceptionWebService
 
Nodes 3 and 4 are showing as unavailable. The zip file doesn't seem to include them either. Is this intentional?
 
Thanks,
 
Mike
QuestionWill this work for C# Web services?memberElCaito2 Feb '10 - 18:18 
I have a C# web service I want to use this for and I am not able to get it to work. I've managed to open the project and make a DLL. I've placed the DLL into my web service, added the entries into my web.config as explained numerous times and as shown in the txt file that came with the project. But when I run my web service, none of my exceptions are triggering this dll!
Maybe it's because my web service is already handling exceptions quite well, but I would like to use the sample project to place a better log file and email.
Can someone please help me? Thanks
GeneralIIS 7.5 problemmemberMember 26080011 Feb '10 - 22:50 
Using IIS 7.5 i was getting
"Error 'Object reference not set to an instance of an object.' while generating exception string"
in the emails and logfile instead of the exception details.
 
I have tracked down the issue to the WebCurrentUrl function in Handler.vb
However i cannot make the friendly error page show when i set the "LogToUI" value="True" in the web.config
 
i have modified as follows:
 
Private Function WebCurrentUrl() As String
Dim strUrl As String = ""
If Not HttpContext.Current.Request.ServerVariables Is Nothing Then
With HttpContext.Current.Request.ServerVariables
If Not .Item("server_name") Is Nothing Then
strUrl = "http://" & .Item("server_name")
End If
If Not .Item("server_port") Is Nothing Then
If .Item("server_port") <> "80" Then
strUrl &= ":" & .Item("server_port")
End If
End If
If Not .Item("url") Is Nothing Then
strUrl &= .Item("url")
End If
If Not .Item("query_string") Is Nothing Then
If .Item("query_string").Length > 0 Then
strUrl &= "?" & .Item("query_string")
End If
End If
End With
End If
Return strUrl
End Function

GeneralRe: IIS 7.5 problemmemberRajesh Rolen13 Sep '11 - 1:34 
Thanks a lot.
This resolved my issue...
 
Thanks
Rajesh Kumar Rolen
www.DotNetAcademy.blogspot.com
GeneralOutOfMemoryException fix with large webservice responsesmemberJorsche17 Nov '09 - 12:35 
I was getting an OutOfMemoryException error when sending back a 50mb file back through a webservice method. Doing a buffered copy fixed it for me (code copied from a google search)...
    Private Sub Copy(ByVal src As Stream, ByVal dest As Stream)
        Dim size As Integer = &H2000
        If ((src.CanSeek)) Then
            size = Math.Min(CInt((src.Length - src.Position)), &H2000)
        End If
        Dim buffer As Byte() = New Byte(size - 1) {}
        Dim n As Integer
        Do
            n = src.Read(buffer, 0, buffer.Length)
            dest.Write(buffer, 0, n)
        Loop While n <> 0
    End Sub

GeneralSoap Extension with MTOMmemberjstark11021 Sep '09 - 6:19 
Hi,
 
I have created a web service that uses MTOM, and combining it with this project above.
 
I noticed that MTOM wasn't allowing the web extension to pick up the stream. It was closing the stream before it could be read. I am guessing a bug in the framework. So I overrode the close method so that is stayed open until it could be read. (See below)
 
Class ExtMemoryStream
    Inherits System.IO.MemoryStream
 
    ''' <summary>
    '''   Overriden close method.
    ''' </summary>
    ''' <remarks>Does nothing.</remarks>
    <Obsolete("This method does not close the stream.")> _
    Public Overloads Overrides Sub Close()
    End Sub
 
    ''' <summary>
    '''   Closes the current stream and releases any resources (such as sockets and
    '''   file handles) associated with the current stream.
    ''' </summary>
    ''' <param name="close">True if the Stream should be closed.</param>
    Public Overloads Sub Close(ByVal close As Boolean)
        If close Then
            MyBase.Close()
        End If
    End Sub
 
    ''' <summary>
    '''   Releases all resources used by the System.IO.Stream.
    ''' </summary>
    Public Shadows Sub Dispose()
        ' Close the stream, as the base Dispose cannot call Close anymore
        MyBase.Close()
        MyBase.Dispose()
    End Sub
End Class
 
Now I am getting a message that I can't find anywhere and am not sure how to solve. Please help.
 
Exception Type: System.FormatException
Exception Message: WSE2202: The stream is not in a valid format.
Exception Source: Microsoft.Web.Services3
GeneralExcellent PostmemberDolphinCatcher29 Aug '09 - 17:04 
Jeff this is exactly what i have been looking for and integrated into my web server very easy, thanks for the post.
QuestionWCF integrationmemberStephen Davies28 Apr '09 - 15:37 
Much time has passed since your original posting of this article and I still find myself still implementing this handler in aspnet 3.5 web applications, nothing out there (that I can find anyway) meets my needs so well, excellent job Jeff.
 
I have recently had a need to implement the same exception handling specifically in a WCF server and wondered if Jeff or anyone out there has implemented a UehWCFExtension similar to the UehSoapExtension?
QuestionHow to log in Application logmemberhohodada19 Feb '09 - 21:43 
Hi,
 
I have followed the steps in readme file to test my Web Service. Actually, I just want to log the error event in the Application Log only. Therefore, I just set the key "LogToEventLog" to true only.
 
And then I wrote a test web method (a recursive method) to make it throw System.StackOverflow error. However, it is still the non readable contents in that error log (EventType clr20r3, P1 aspnet_wp.exe, P2 2.0.50727.3053, P3 4889ded7, P4 betexchange, P5 2.0.3338.27037, P6 499e553a, P7 162, P8 0, P9 system.stackoverflowexception, P10 NIL.)
 
Could anyone advise me if I miss something to test with this ASPUnhandledException.dll?
 
Thanks a lot.
GeneralIIS7 Problems [modified]memberGregSawin4 Sep '08 - 9:03 
When I upgraded to IIS7 the exception handling stopped working. No notice of it's incompatibility or error message, it just seems to ignore the custom module. Setting the app pool to classic resolves the issue but I want to run my app in the normal mode. I found a partial solution from the first item on this page: http://learn.iis.net/page.aspx/381/aspnet-20-breaking-changes-on-iis-70/[^]
 
After making that change emails do get generated but the user never sees anything other than the standard error page.
 
Has anyone else gotten this to work in IIS7 w/o reverting to classic mode?
 
modified on Friday, October 30, 2009 3:17 PM

GeneralRe: IIS7 ProblemsmemberJefke013 Aug '09 - 22:19 
Yes, I got is working.
1) Remove the customer error module
2) debug the handler coding:
I used lowercase of variable names (ServerVariables)
after changing to uppercase it worked.
 
3)Also check the permissions to send mails
 
string url;
HttpRequest request = HttpContext.Current.Request;
url = "http://" + request.ServerVariables["SERVER_NAME"].ToString();
if (request.ServerVariables["SERVER_PORT"].ToString() != "80")
url += ":" + request.ServerVariables["SERVER_PORT"].ToString();
 
url += request.ServerVariables["URL"].ToString();

if (request.ServerVariables["QUERY_STRING"].Length > 0)
url += "?" + request.ServerVariables["QUERY_STRING"].ToString();
return url;
 
*

GeneralRe: IIS7 ProblemsmemberTom McDonald21 Oct '09 - 6:57 
I gave up on trying to get this working on IIS7 and instead went with the solution shown here http://www.asp.net/learn/videos/video-417.aspx[^]
GeneralRe: IIS7 ProblemsmemberTom McDonald15 Oct '09 - 11:32 
When you say the 'first item' are you referring to '1. ASP.NET applications require migration when specifying configuration in httpModules or httpHandlers'?
GeneralRe: IIS7 ProblemsmemberGregSawin30 Oct '09 - 9:19 
Yes
GeneralRe: IIS7 Problems - GOT IT WORKINGmemberswank-dog15 Dec '10 - 10:32 
I don't know why, (don't have remote debugging working on staging server) but the HandleException method in Handler.VB was getting a null ref exception and dying before any of the actions took place.
I just added a null check for e.Innerexception and I was able to get the friendly page (although I'm not getting the stack trace so i used Log4Net to log it to a file before the ASPUnhandledExcpetion is called in Page_Error event in my base page).
 

Changed Handler.VB
Try
      _strException = ExceptionToString(ex)
      _strExceptionType = ex.GetType.FullName
 
      If _strExceptionType = _strRootException Or _strExceptionType = _strRootWsException Then
        If Not ex.InnerException Is Nothing Then
          _strExceptionType = ex.InnerException.GetType.FullName
        End If
      End If
    Catch e As Exception
      _strException = "Unhandled ASPX Error: '" & e.Message & "' while generating exception string. '" & e.StackTrace & "'"
      If Not e.InnerException Is Nothing Then
        _strException += "'" & e.InnerException.Message & "'"
      End If 
    End Try
 
Global.asax
  void Application_Error(object sender, EventArgs e)
        {
          // Code that runs when an unhandled error occurs
          try
          {
            Exception objErr = Server.GetLastError();
            string err = "Unhandled Application Error caught in Application_Error event. " +
                        " Error in: " + Request.Url.ToString() +
                        " Error Message: " + objErr.Message.ToString() +
                        " Stack Trace: " + objErr.StackTrace.ToString();
            Log.Error(err);
            ASPUnhandledException.Handler ueh = new ASPUnhandledException.Handler();
            ueh.HandleException(objErr);
          }
          catch(Exception ex)
          {
            Log.Error("ExceptionCaught trying to handle an untrapped error via ASPUnhandledException(): ", ex);
          }
        }
ADWBaseContentBase.cs
        public void Page_Error(object sender, EventArgs e)
        {
          Exception objErr = Server.GetLastError().GetBaseException();
          string err = "Error Caught in Page_Error event. " +
              " Error in: " + Request.Url.ToString() +
              " Error Message: " + objErr.Message.ToString() +
              " Stack Trace: " +
                            objErr.StackTrace.ToString();
          Log.Error(err);
          ASPUnhandledException.Handler ueh = new ASPUnhandledException.Handler();
          ueh.HandleException(objErr);
        }

GeneralCould not find schema information for....memberOldSeaDog27 Apr '08 - 9:53 
I'm using Visual Web Developer under XP, NOT IIS, and get messages (not errors or warnings) "Could not find schema information for the element 'UnhandledException' and again for each of the elements under <UnhandledException>.
 
I have a number of entries under <configSections> such as Section Groups, Section Name, etc. and I added the line for 'UnhandledException' just before the </configSections> trailer. This trailer was followed by all the entries in <UnhandledException> through </UnhandledException>.
 
Is this a VWD problem or something else?
 
Thanks.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 21 Dec 2004
Article Copyright 2004 by wumpus1
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid