ASP.NET โ Error Handling โ Catch, Log, and Display Application Errors Gracefully
Introduction โ Why ASP.NET Error Handling Is Essential
In every web application, errors are inevitableโwhether due to invalid input, database failures, or unhandled exceptions. ASP.NET provides a robust mechanism to handle, log, and display errors in a way that enhances debugging and improves user experience without exposing sensitive stack traces.
In this guide, youโll learn:
- How to handle exceptions in ASP.NET Web Forms
- How to use
try-catch,Page_Error,Application_Error, andcustomErrors - How to log errors and show user-friendly messages
- Difference between Debug mode and Release mode in error visibility
Types of Errors in ASP.NET
| Error Type | Description |
|---|---|
| Compilation Errors | Syntax issues or missing references |
| Runtime Errors | Exceptions that occur during execution |
| Logic Errors | Errors due to incorrect logic, not detected by .NET |
| HTTP Errors | Errors like 404 (Not Found), 500 (Server Error), etc. |
Example โ Basic try-catch Block
protected void Page_Load(object sender, EventArgs e)
{
try
{
int x = 0;
int y = 10 / x; // Will throw DivideByZeroException
}
catch (DivideByZeroException ex)
{
lblError.Text = "Math Error: Division by zero is not allowed.";
// Log error to database or file
}
}
Explanation:
tryblock holds risky codecatchhandlesDivideByZeroExceptionlblError.Textshows a custom error message
Output:
User sees: โMath Error: Division by zero is not allowed.โ
Page-Level Error Handling โ Page_Error
This method catches any unhandled error at the page level.
protected void Page_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Server.ClearError();
Response.Redirect("ErrorPage.aspx");
}
Explanation:
GetLastError()fetches the latest exceptionClearError()prevents further error propagation- Redirects user to a friendly error page
Application-Level Error Handling โ Application_Error
Defined in Global.asax, it handles all unhandled exceptions in the application.
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// Log error to database, email, or event viewer
Server.ClearError();
Response.Redirect("~/ErrorPage.aspx");
}
Ideal for: Centralized error logging and custom redirection for production apps.
Configure customErrors in web.config
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="ErrorPage.aspx">
<error statusCode="404" redirect="NotFound.aspx" />
</customErrors>
</system.web>
</configuration>
Explanation:
mode="On": Enables custom error handlingdefaultRedirect: Redirects all errors to a single page- Specific redirect for HTTP
404errors
Modes:
On: Show custom error pageOff: Show detailed ASP.NET errorsRemoteOnly: Show detailed errors locally, custom errors remotely
Custom Error Page Example (ErrorPage.aspx)
<h2>Oops! Something went wrong.</h2>
<p>We apologize for the inconvenience. Please try again later.</p>
You can display generic messages and avoid exposing stack traces.
Using Trace for Debugging
Enable page tracing in development for error visibility:
<%@ Page Language="C#" Trace="true" %>
Output: Shows detailed execution info, exceptions, and variable states at the bottom of the page (only visible to developers).
Best Practices for ASP.NET Error Handling
Do:
- Use
try-catcharound risky operations - Log errors to file, DB, or third-party services
- Use
customErrorsin production
Avoid:
- Displaying full exception details to end-users
- Swallowing exceptions silently
- Hardcoding error messages in markup
Summary โ Recap & Next Steps
ASP.NET error handling helps manage unexpected issues gracefully while maintaining a professional user experience. From try-catch blocks to centralized Application_Error, these features ensure your app doesn’t crash silently or expose stack traces.
Key Takeaways:
- Handle page-level and app-wide exceptions with
Page_ErrorandApplication_Error - Use
customErrorsinweb.configfor custom error redirection - Avoid showing raw exceptions to end users
Real-world Use Cases:
- Redirect 404 errors to search pages
- Email logs to administrators
- Log exceptions for auditing and debugging
FAQs โ ASP.NET Error Handling
What happens if I donโt handle an exception in ASP.NET?
The application may crash, or ASP.NET will show a yellow screen of death (YSOD). Use Application_Error or customErrors to prevent that.
How do I show user-friendly messages?
Catch the exception and show a simplified message using lblError.Text or redirect to a friendly page.
Where should I log unhandled exceptions?
Use Application_Error to log to a database, text file, or error-tracking tools like ELMAH or Serilog.
Can I create different error pages for different status codes?
Yes. Use <error statusCode="404" redirect="NotFound.aspx" /> in web.config.
Share Now :
