O'Reilly logo

ASP.NET 2.0 Cookbook, 2nd Edition by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.3. Pinpointing the Cause of an Exception

Problem

You want to identify problems only when an exception occurs.

Solution

Dynamically turn on page-level tracing from within the Catch block of your exception handler and write to the trace log.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Set Page.Trace.IsEnabled = true in the Catch block of your exception handler.

  2. Write to the trace log by using a Trace.Write of the form Trace.Write("Exception", "Message", exc).

Figure 13-3 shows the appearance of some exception information in the trace sequence. Examples 13-4, 13-5 through 13-6 show the .aspx file and VB and C# code-behind files for the application that produces this result.

Discussion

ASP.NET processes and displays trace statements only when tracing is enabled. However, what if you don’t want to see the trace log all the time but only when an exception occurs? The answer is to turn tracing on dynamically for the page. You can then write the exception information to the trace log and debug the problem from there.

Our example that illustrates this solution is primitive, in that it forces an exception. Though this is not something you would normally do in production code, it does allow us to show the infrastructure needed to control tracing at runtime.

When the exception occurs, the exception handler enables the trace output by setting Trace.IsEnabled to true. For the exception information to appear in the trace sequence, you must use a Trace.Write of the form ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required