473,468 Members | 1,472 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Exceptions in Web Apps?

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?

Am I approaching the whole issue incorrectly?
If so, could somebody tell me how are exception handled
in Web apps?

Thanks a lot,
Juan Dent
Nov 17 '05 #1
2 2522
"Juan Dent" <ju***@dev.com> wrote in message
news:03****************************@phx.gbl...
| 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.Ge tName.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 <ww********@altaircom.net>"
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

--
Michal A. Valasek, Altair Communications, http://www.altaircom.net
Please do not reply to this e-mail, for contact see http://www.rider.cz
Nov 17 '05 #2
it's not a good idea to let the application object handle page exceptions.
why have the exception bubble to the top? by the time the exception reaches
the top, the context of the error is properly lost and the application
object cannot possibly remedy the situation. Instead, you should attempt to
always handle the exceptions at the point at which they occur in the code
with a catch block or next at the page level by chaining to the error event
like so this.error += new handler(page_error).
in the page_error handler you put code to handle the exception at the page
level. all exceptions occuring in the page will then be handled at the page
level assuming that your try catch block failed to catch the exception at
the code level. if you determine then that you cannot handle the exception
at the page level because of context, then you may rethrow the error to the
next level, possibly the appdomain layer, session layer and then to the
application layer. this layered approach provides a structured way in
allowing each layer a chance to handle the exception or pass it on up to the
caller.
"Michal A. Valasek" <ne**@altaircom.net> wrote in message
news:#M**************@TK2MSFTNGP10.phx.gbl...
"Juan Dent" <ju***@dev.com> wrote in message
news:03****************************@phx.gbl...
| 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.Ge tName.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 <ww********@altaircom.net>"
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

--
Michal A. Valasek, Altair Communications, http://www.altaircom.net
Please do not reply to this e-mail, for contact see http://www.rider.cz

Nov 17 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

33
by: Steven Bethard | last post by:
I feel like this has probably been answered before, but I couldn't find something quite like it in the archives. Feel free to point me somewhere if you know where this has already been answered. ...
9
by: Marty McDonald | last post by:
If I invoke a web service, and it throws an exception, I can see the exception if the client app is a .Net app. However, if the client app is not a .Net app, I only receive the HTTP 500 error. I...
59
by: kk_oop | last post by:
Hi. I wanted to use exceptions to handle error conditions in my code. I think doing that is useful, as it helps to separate "go" paths from error paths. However, a coding guideline has been...
2
by: thechaosengine | last post by:
Hi everyone, Is there anyway to create some sort of catch-all in windows forms applications that could ensure that no unexpected exceptions bring down an application? For example, perhaps...
5
by: Miyra | last post by:
Hi. I'm working with an app that uses exceptions for control flow. These are code blocks where exceptions are thrown/caught regularly. A couple hundred exceptions occur per hour and they're caught...
16
by: Einar Høst | last post by:
Hi, I'm getting into the Trace-functionality in .NET, using it to provide some much-needed logging across dlls in the project we're working on. However, being a newbie, I'm wondering if some...
10
by: Cool Guy | last post by:
Consider: void Start() { if (!TryToDoSomething()) ShowErrorMessage(); }
4
by: ___Newbie___ | last post by:
Hello, Does every error encountered during try() block is handled by catch(Exception e) ? Do I have to catch every aspect or every detail of exception? e.g. catch (IOException io) catch...
2
by: Eric Sabine | last post by:
I built a generic exception handler form which allows the user to get information from it, print it, email it, etc. for exceptions for which I explicitly didn't handle in code, such as missing...
1
by: Diego F. | last post by:
I use to show the error messages that I get in a try block. try { ... } catch (Exception ex) { ... (ex.Message); }
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.