Handling Unhandled Errors in Web Applications


If you handle unhandled errors, doesn't that make them handled, by definition? The answer is "not quite," as you'll see shortly.

When the ASP.NET framework detects an unhandled exception, it cancels the response for the page that triggered the exception. Then it fires the application's error event in the Global.asax file. From here you can find out what exceptions you have and even clear the exceptions, if you like. Nothing can resurrect the page where you had the exception, but by clearing the exceptions you can prevent the application from sending an error page back to the user . So one way to handle unhandled exceptions is to clear them from the errors collection.

The other way to handle unhandled exception is to print a nice error message. Sometimes no matter how hard you try to debug your program, something always ends up breaking. In that case you can tell ASP.NET to display a custom error page when an unhandled exception occurs.

In summary, there are three things you can do with exceptions. You can handle them with try/catch blocks; you can handle them in the application's error event; or you can design a nice page for your user in case something gets missed. Let's add all three mechanisms to the sample application.

To add error catching in the sample application:

  1. Choose Project > Add New Item from the menu bar. Enter exceptionclasses.cs for the file name ( Figure 11.35 ).

    Figure 11.35. This time, instead of creating a class, we're just adding an empty file. This is because when you tell the wizard to add a class file, the wizard adds a class definition as well. We don't want a single class definition. We want this module to be a repository for any exception class we define in the future.

    graphics/11fig35.gif

  2. Add the code in Figure 11.36 . This code defines the NotAMemberOfRoleException custom exception. The class has a single member with the name of the role that was requested .

    Figure 11.36 NotAMemberOfRoleException is a simple exception object with a field called RoleRequested that tells the error handling code what role was needed for the function to execute.
     using System; namespace exceptionsproject {    public class NotAMemberOfRoleException    : ApplicationException    {       public string RoleRequested;    } } 
  3. In the High security task button, let's modify the code so that when a security error occurs we throw the NotAMemberOfRoleException exception instead, with information about the role that was needed to execute the function. Right-click on the secured.aspx file and choose View Code from the pop-up menu. Find the btnHighTask_Click function and add the highlighted code from Figure 11.37 .

    Figure 11.37 The High task button catches the general security exception and then throws the more specific NotAMemberOfRoleException to the caller so that they know what role the function was expecting.
     private void btnHighTask_Click( object sender, System.EventArgs e) {  try   {  PrincipalPermission perm = new       PrincipalPermission(null,"Admin");       perm.Demand();  }   catch(   System.Security.SecurityException ex)   {   NotAMemberOfRoleException newex =   new NotAMemberOfRoleException();   newex.RoleRequested = "Admin";   throw newex;   }  } 
  4. Right-click on the file Global.asax and choose View Code from the pop-up menu.

  5. Locate the function Application_Error and add the highlighted code from Figure 11.38 to it. This code checks to see if the error generated was a NotAMemberOfRoleException . If so, it clears the errors and sends a friendly message to the client.

    Figure 11.38 If you were to examine Contex.Error you would just see a generic System.Web.HttpUnhandledException exception. To get at the NotAMemberOfRoleException you need to call the GetBaseException function.
     protected void Application_Error( Object sender, EventArgs e) {  if (Context.Error.GetBaseException()   is NotAMemberOfRoleException)   {   string role =   ((NotAMemberOfRoleException)   Context.   Error.   GetBaseException()).RoleRequested;   Response.Write(   "You can upgrade now to " + role   + " for only 9.95 a month!");   Context.ClearError();   }  } 
  6. The only thing missing is a custom error page for when there are unhandled exceptions, and in fact there's at least one unhandled exception. Select Project > Add Web Form from the menu bar.

  7. In the dialog in Figure 11.39 enter niceerror.aspx for the file name.

    Figure 11.39. niceerror.aspx will be our custom error page. If there's an unhandled exception that we didn't account for, they'll see this nice error page.

    graphics/11fig39.gif

  8. Add a label control to the niceerror.aspx page that gives a friendly error message. I chose "Oops!" for mine ( Figure 11.40 ).

    Figure 11.40. You'll probably want to have more than Oops! for your custom error page, but you get the idea.

    graphics/11fig40.gif

  9. Open the Web.config file and locate the section that reads customErrors. Replace the section with the code in Figure 11.41 .

    Figure 11.41 It's very simple to tell ASP.NET what our custom error page is and when to display it, it's just a matter of adjusting some settings in Web.config.
     <customErrors defaultRedirect= "niceerror.aspx" mode="On" /> 

graphics/tick.gif Tips

  • The customErrors section in Web.config has three settings: RemoteOnly, On, or Off. The default is RemoteOnly, which means: Display a custom error page only when a machine outside your server gets the error. If you're testing the pages in your own server then you'll get a detailed error. Off means that ASP.NET will always display a detailed error and never a custom error. On is the opposite , and means: Always display a custom error. In the sample code we're changing the setting to On so that you can see the custom error while debugging, but normally RemoteOnly is what you want.

  • To test the application, log in as Douglas Adams and try both buttons . The Low security task button should display the custom error page. The High security task should display a nice message asking the you to subscribe to Admin rightsfor only $9.95 a month.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net