ASP.NET Basics Part 10: Making Exceptions - Exceptionally Clever
(Page 3 of 12 )
Let's look at the simple approach first. As explained earlier, this technique merely involves sending the user to a generic page when an exception occurs. There are two basic steps in this process: creating a page containing a generic error message, and modifying the server configuration so that the page is invoked when an exception occurs.
Let's illustrate this process with a simple example. Here's an ASP.NET script that divides a number by zero, a process guaranteed to make any programming language scream in anguish.
<script language="c#" runat="server">
void
Page_Load() {
<P align=left>
<P align=left>int a = 19;
int b = 0;
int c = a/b;
<P align=left>
<P align=left>}
</script>
<html>
<head></head>
<body>
<asp:label
id="output" runat="server"
/>
</body>
</html>
Here's the output:

Ugly, huh?
Now, create the page that is shortly going to replace the gobbledygook above (call it "error.aspx"):
<% @ Page Language="C#"
%>
<html>
<head><title>Error
</title></head>
<body>
<asp:label id="errorMessage"
runat="server"
value="An error occurred. Please exit in single file,
turning the light off after you leave."
/>
</body>
</html>
Next, you need to tell the Web server that it should load the page above whenever an exception occurs. This can be done by setting a value for the <customErrors> element in the "web.config" file. This file, usually located in the same directory as your ASP.NET scripts, allows you to configure some aspects of your application.
Here's what your "web.config" file should look like:
<configuration>
<system.web>
<customErrors
defaultRedirect="error.aspx" mode="On"
/>
</system.web>
</configuration>
The "defaultRedirect" attribute of the <customErrors> element allows you to specify the error page to be displayed in the event of an exception. The "mode" attribute allows you to control the behaviour of the server in the event of an exception, and can take any of the following three values: "On", which will display the custom error page defined in the
"defaultRedirect" attribute under all conditions; "Off", which will display the standard exception dump under all conditions; and "RemoteOnly", which will display the exception dump when the script containing the erroneous code is accessed from the local system itself, and the custom error page when it is accessed over the network or Internet. This allows a developer to debug errors without having to worry about their visual impact on end users, as they will only get to see the error page defined in the "defaultRedirect" attribute.
Now, if you retry the script above, you should see your custom error page instead of the standard exception page:

Next: A Custom Job >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire