Table of Contents
Bugs and errors are an inevitable part of building any complex web application. Thankfully ASP.Net provides a robust set tools and techniques to help you smoothly tackle them.
In this guide, we‘ll explore hands-on how to leverage debugging, tracing and error handling in ASP.Net to create resilient, production-grade apps.
I‘ll share real-world insights and data so you can make optimal decisions for your unique needs.
Let‘s get started!
Why Debugging, Tracing and Error Handling Matters
Before jumping into the how, it‘s important to level set on why robust debugging, tracing and error handling capabilities matter:
1. Reduce troubleshooting time
Debugging helps diagnose issues 5x faster on average compared to pure logging approaches as per Forrester research.
2. Improve customer experience
63% of users will abandon a mobile site that crashes or errors per Data Calculator stats. Elegant error handling ensures your UI never fully breaks.
3. Minimize business losses
On average, app downtime costs $5,600 per minute as per Aberdeen Group. Effective tracing helps restore services faster.
Clearly, having robust diagnostics and error handling is imperative both for developer productivity and meeting business KPIs.
With that context on why it matters, let‘s deep dive on how to implement debugging, tracing and error handling effectively in ASP.Net.
Debugging in ASP.Net
Debugging refers to executing an application in a controlled step-by-step manner to uncover issues.
ASP.Net debugging is enabled through breakpoints.
Breakpoints pause execution at a particular line so you can examine application state – variables, memory, database connections etc.
This helps figure out what may be breaking in the app without having to pepper logging statements everywhere.
Adding Breakpoints
There are two ways to add breakpoints in Visual Studio while debugging ASP.Net apps:
1. Code editor margin
Simply click on the left margin of a code editor line where you want to pause. This will set a red breakpoint dot.
2. Debug menu
Navigate to Debug > New Breakpoint. This opens a breakpoint configuration dialog through which you can filter very specifically where you want breaks.
For example, break only when variable xyz matches a certain value.

Key Tip: You can set conditional breakpoints based on expressions, hit counts, filters etc. to make debugging sessions hyper-efficient.
Starting a Debugging Session
Once breakpoints are set, you can start a debugging session via:
1. Debug menu
Navigate to Debug > Start Debugging
2. F5 shortcut
Simply pressing F5 will launch debugging. Most devs have this keyboard shortcut memorized!
Execution will then pause automatically at the first breakpoint allowing inspection of application state.
Debugging Session Walkthrough
Let me walk you through a sample ASP.Net debugging session to make this concrete:
1. Set breakpoint
I set a breakpoint in Page_Load on this line:
Log("User logged in");

2. Launch debugger
I initiate debugging via F5.
3. Execution pauses on breakpoint
Code pause on the Log line:

Notice the yellow color highlighting. This visual indicator tells me debugging is halted on this line.
4. Inspect variables
I can now hover over variables to view state.
For example, hovering on Request.User prints -> [email protected]:

This helps validate if the user object was set correctly.
5. Step through code (F10, F11)
I can also step through subsequent lines one-by-one using F10 or F11 rather than resuming full execution.
Stepping through provides precision in analyzing logic flow.
6. Set watches
Additionally, I can set watches on critical variables to track values – without having to continuously hover.
Watches help spot anomalies as code progresses.
For example, if expect tokenValid to stay true but watches print false at some line, that‘s a red flag!
7. Edit code (fixes)
I can directly edit code logic in the debugger itself if I find bugs.
The ability to tweak code without having to stop/recompile saves enormous time.
8. Continue execution (F5)
Finally, pressing F5 continues code execution till the next breakpoint.
The debugger seamlessly lets you iterate through the find/fix cycle efficiently till the bug is squashed!
Debugging Benefits
Some key benefits of debugging versus pure logging:
- Faster diagnosis – No need to piece together logs, replay issues
- Root cause analysis – Inspect state at point of failure
- Fixes on the fly – Tweak logic in real-time without recompiling
- Step through execution – Validate app behavior incrementally
Factor in your needs to determine if debugging is right for a particular scenario.
Now that we‘ve covered debugging, let‘s explore tracing.
Tracing in ASP.Net
Tracing provides diagnostic data about ASP.Net application execution and page processing at runtime.
When enabled, key tracing data is logged for every request:
- Timestamp
- Request details – URL, headers etc.
- Processing time
- Performance data
- Errors if any
Let‘s understand how to configure tracing.
Enabling Application Level Tracing
To enable application-wide tracing:
-
Open web.config
-
Inside
<system.web>, add a<trace>node:<trace enabled="true" requestLimit="10"/>enabledactivates tracingrequestLimitcontrols how many requests are logged
-
Set
localOnly=falseto view remotely
That‘s it! This is the easiest way to start tracing your app.
With above config, browsing to yoursite/trace.axd will display detailed logs per request.

From performance data to errors, this provides invaluable insights into app issues.
Let‘s now see how to implement more fine-grained page-level tracing.
Enabling Page Level Tracing
Application tracing provides high-level logs. But for more granular, page-specific data you can enable page-level tracing.
This can be activated directly in the page handler via:
<%@ Page Trace="true" ... %>
On setting Trace=true, detailed trace data is dumped at the bottom of the rendered page itself!

The page trace provides incredibly fine-grained diagnostics on page execution – which events fired in what order, performance of individual blocks, errors etc.
This data is invaluable for identifying page-specific bottlenecks.
Tracing Pros and Cons
Let‘s summarize key advantages and limitations:
Pros
- Lightweight implementation
- Request-level diagnostics
- Performance insights
- Errors visible easily
Cons
- Can impact app performance if overused
- Requires manual analysis
- Does not log custom traces
Factor in these tradeoffs for your usage patterns.
Additionally, third party log analyzers like ELMAH can also be integrated to enhance default tracing capabilities.
With clarity on tracing, let‘s round off by covering error handling.
Error Handling Best Practices
Bugs aside, even the most robust applications can encounter unanticipated errors – bad user input, network blips etc.
Handling errors gracefully is thus crucial for any production app.
Let‘s explore error handling capabilities and recommended strategies in ASP.Net.
Custom Error Pages
By default, ASP.Net displays an ugly but innocuous yellow error screen on unhandled exceptions.
This is usable but breaks branding continuity and fails to instill confidence if users see it.
Custom error pages help solve this elegantly.
To create a custom error page:
-
Add a custom error HTML file
For example
myErrorPage.html -
Design user-friendly content
"Sorry, some error occurred while processing your request"
-
Set as default error handler in web.config:
<customErrors mode="On" defaultRedirect="myErrorPage.html"/>
Now anytime an uncaught exception happens, ASP.Net will display your custom page preserving UX continuity!
Unhandled Error Handling
In addition to general exceptions, for unanticipated errors like direct URL not found (404), ASP.Net lets you handle via Application_Error event.
Steps:
-
Implement
Application_Errorhandler in Global.asax -
Check last exception and respond accordingly:
void Application_Error(Object sender, EventArgs e) { var exc = Server.GetLastError(); if (exc is HttpException && exc.GetHttpCode() == 404) { //show custom 404 page Server.Transfer("~/custom404.html"); } }
Now anytime a random incorrect URL is accessed, custom 404 page will be displayed through above logic rather than IIS default.
This provides a smooth experience even for edge cases.
Centralized Error Logging
In addition to displaying user-friendly errors, logging errors is vital for diagnostics.
ASP.Net enables centralized logging of all unhandled errors to a local text file via Application_Error event.
Sample logging implementation:
void Application_Error(Object sender, EventArgs e) {
var exc = Server.GetLastError();
string err = exc.Message + "\n" + exc.StackTrace;
File.WriteAllText(@"C:\appErrors.txt", err);
Server.Transfer("~/errorPage.html");
}
This logs any errors along with stacktraces to C:/appErrors.txt which can then be analyzed to fix root causes.
The log can be configured to go to more robust storage like databases as well.
Integrating ELMAH
While default error handling capabilities may suffice initially, as complexity increases, integrating a dedicated module like ELMAH (Error Logging Modules and Handlers) is recommended.
ELMAH enhances what ASP.Net provides out-of-the-box:

- Centralized error log viewing
- Log searches
- Alert integrations
- Custom logging
- UI flexibility
- User management
- API access
Evaluate modules like ELMAH to raise error handling sophistication over time.
Putting It All Together
We‘ve covered quite a bit of ground on the complete debugging, tracing and error handling framework in ASP.Net.
Let‘s summarize the key capabilities:
- Debugging to diagnose issues live via breakpoints
- Tracing for request-level diagnostics
- Page tracing for targeted data
- Custom error pages to preserve UX
- Centralized logging for error analytics
Factor in your application complexity, traffic patterns, team skills and business requirements to devise an appropriate debugging, tracing and error handling strategy.
Interested to learn more? Check out my advanced article on Using Tracing, Debugging and Monitoring for Robust ASP.Net Apps.
I hope this guide gives you a comprehensive overview of debugging, tracing and error handling in ASP.Net. Feel free to reach out if any part needs more clarification.
Happy building resilient web apps!