| Hi,
|
| How does one handle exceptions in a Web application? For
| instance, I have a Page_Load method that throws an
| ArgumentNullException on some ocassions and I have set
| the Web.config file with a section like so:
|
| <customErrors mode="On" defaultRedirect="ErrorForm.aspx"/>
|
| From that page, how can I determine what kind of
| exception (and the exception object itself) was thrown?
I can recommend to handle errors in Application_Error event handler and to
use the error page only to inform user.
The following is code I use for all my applications. It checks if custom
errors are enabled (if no, it expects that's a development server and does
not do anything) and then sends all available details by e-mail to person
specified by web.config variable "Mail.Webmaster". Written in VB.NET:
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
'-- Ignore HTTP errors (ie. 404) and damaged viewstate
If Server.GetLastError.GetType() Is GetType(System.Web.HttpException)
Then Return
If Server.GetLastError.ToString.IndexOf("View State is invalid") > -1
Then Return
If Server.GetLastError.ToString.IndexOf("viewstate is invalid") > -1
Then Return
'-- Check if custom errors are enabled
Dim xDoc As New System.Xml.XmlDocument
xDoc.Load(Server.MapPath("/web.config"))
If Not
xDoc.SelectSingleNode("/configuration/system.web/customErrors[@mode='Off']")
Is Nothing Then Return
'-- Generate text of e-mail message
Dim SB As New System.Text.StringBuilder
Dim S As String
SB.Append("Time:\n" & Now.ToString("yyyy-MM-dd HH:mm:ss"))
SB.Append("\n\nVersion:\n" &
System.Reflection.Assembly.GetExecutingAssembly.GetName.Version.ToString())
SB.Append("\n\nRequested URL:\n" & Request.Url.ToString)
SB.Append("\n\nException:\n" & Server.GetLastError.ToString)
SB.Append("\n\nRemote host:\n" & Request.UserHostAddress)
SB.Append("\n\nUser agent:\n" & Request.UserAgent)
SB.Append("\n\nAuthentication:\n" &
DirectCast(IIf(Request.IsAuthenticated, "yes, as " &
Context.User.Identity.Name, "no"), String))
SB.Append("\n\nServer variables:")
For Each S In Request.ServerVariables.Keys
SB.Append("\n" & S & " = " & Request.ServerVariables(S))
Next
SB.Append("\n\nPOST data available:")
For Each S In Request.Form.Keys
SB.Append("\n" & S & " = " & Request.Form(S))
Next
'-- Send e-mail message
Dim MX As New System.Web.Mail.MailMessage
MX.From = "WWW-Daemon <
[email protected]>"
MX.To = ConfigurationSettings.AppSettings("Mail.Webmaster")
MX.Subject = "Error in " & Request.Url.Host
MX.Body = SB.ToString.Replace("\n", vbCrLf)
System.Web.Mail.SmtpMail.Send(MX)
End Sub