๐Ÿ› ๏ธ ASP.NET Error Handling & Debugging
Estimated reading: 4 minutes 82 views

โ— 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, and customErrors
  • 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 ErrorsSyntax issues or missing references
Runtime ErrorsExceptions that occur during execution
Logic ErrorsErrors due to incorrect logic, not detected by .NET
HTTP ErrorsErrors 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:

  • try block holds risky code
  • catch handles DivideByZeroException
  • lblError.Text shows 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 exception
  • ClearError() 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 handling
  • defaultRedirect: Redirects all errors to a single page
  • Specific redirect for HTTP 404 errors

๐Ÿ“Œ Modes:

  • On: Show custom error page
  • Off: Show detailed ASP.NET errors
  • RemoteOnly: 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-catch around risky operations
  • Log errors to file, DB, or third-party services
  • Use customErrors in 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_Error and Application_Error
  • Use customErrors in web.config for 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 :
Share

โ— ASP.NET โ€“ Error Handling

Or Copy Link

CONTENTS
Scroll to Top