21.2. Global Error Handling

In ASP.NET, an unhandled exception isn't pretty. You see it often when you develop and test pages. The details of the exceptions change, but the red Server Error (shown in Figure 21-1) always grates. In this section, you find options for handling errors on an ASP.NET Web site.

Figure 21-1. A server error at runtime speaks volumes.

Although error stack traces (the exception details) in pages are helpful for developers, it's not polite to foist them on users (refer to Figure 21-1). Additionally, telling hackers too much about your system and paths is dangerous because the bad guys might use the information to worm their way in. In fact, hackers try to cause errors just to exploit them. Ensure that users don't see any details by providing a user-friendly, generic error page. Follow these steps to configure a custom error page.

  1. Add an ASP.NET page that deliberately creates an error condition. Use the following code to throw the exception shown earlier in Figure 21-1.

    Protected Sub Page_Load(ByVal sender As Object, _
      ByVal e As System.EventArgs)
    
       Dim q = From FileName In System.IO.Directory.GetFiles _
        ("c:\doesntexist\", "*.*", System.IO.SearchOption.AllDirectories)
    End Sub
  2. Add <%@ Import Namespace="System.Linq" %> to the top of the .aspx page to keep the LINQ query happy.

  3. Add an HTML page called oops.htm to your project (FileNew FileHTML Page).

    Using an HTML ...

Get ASP.NET 3.5 For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.