asp. net Development Common Common Exception Capture Ways Summary of Attached Source Code

  • 2021-07-10 19:27:29
  • OfStack

This article summarizes common ways to catch exceptions in asp. net development with examples. Share it for your reference, as follows:

In the actual development process, for an application system, it should have its own set of mature exception handling framework, so that when exceptions occur, it can also get the unified handling style, and the exception information can be gracefully fed back to developers and users. As we all know, the exception handling of. net is thrown layer by layer from the bottom to the top according to the way of "exception chain". If we can't judge the boundary of exception as early as possible and catch exception, CLR will automatically help us handle it, but the overhead of this system is very large, so an important principle of exception handling is "early detection, early throwing and early handling". However, the server-side common catch exception handling summarized in this paper can be broadly regarded as an operation at the presentation layer, and it is beyond the scope of discussion to catch specific exceptions at a specific layer.

1. BasePage class processing mode

Override the OnError event in the common base class of the page. In the previous article "asp. net to achieve a very practical custom page base class", Lou Pig has posted the code, so it won't bother. According to experience, many people almost write this when developing, and it is very helpful for debugging and maintenance. It should be noted that for every new page added, its corresponding class must inherit from BasePage class exception handling to work.

2. Global. asax processing mode

As described in 1, exception handling of the BasePage class requires that every aspx class file inherits it, and its applicability and performance are obviously compromised. The Global. asax file defines the common methods, attributes and events of all application objects in asp. net applications. We can implement and process Application_Error events in Global. asax instead of BasePage. The following imitates the exception handling method in BasePage class and implements it as follows:


/// <summary>
///  Error handling : Write a journal , Navigate to the Public Error page 
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_Error(object sender, EventArgs e)
{
  if (Server.GetLastError() == null) return;
  Exception ex = Server.GetLastError().GetBaseException();
  string error = this.DealException(ex);
  DotNet.Common.Util.Logger.WriteFileLog(error, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");
  if (ex.InnerException != null)
  {
    error = this.DealException(ex);
    DotNet.Common.Util.Logger.WriteFileLog(error, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");
  }
  this.Server.ClearError();
  this.Response.Redirect("/Error.aspx");
}
/// <summary>
///  Handle exceptions to write primary exception information to the text log 
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
private string DealException(Exception ex)
{
  this.Application["StackTrace"] = ex.StackTrace;
  this.Application["MessageError"] = ex.Message;
  this.Application["SourceError"] = ex.Source;
  this.Application["TargetSite"] = ex.TargetSite.ToString();
  string error = string.Format("URl : {0}\n How to throw an exception: {1}\n Error message: {2}\n Error stack: {3}\n",
    this.Request.RawUrl, ex.TargetSite, ex.Message, ex.StackTrace);
  return error;
}

The advantage of the above method is that once you write the code, most of the exceptions that occur in the application will be caught and handled by you. Louzhu would like to send a heartfelt feeling here, thanking ms for providing us with such an excellent framework, which is too easy.

3. IHttpModule interface processing

Everyone is very familiar with the treatment methods of 1 and 2. Louzhu basically follows the above two writing methods in actual development, and Louzhu has even excitedly thanked ms because of the all-inclusive treatment method of 2. However, when the asp. net program calls a thread for asynchronous processing, exceptions that are easily thrown in the background thread or thread pool cannot be completely caught by 1 or (and) 2, which involves the handling of uncaught exceptions under asp. net. That is to say, the treatment of anomalies in many large and small projects that Louzhu has done before is incomplete. Is this the evil result of nc building pigs not being planted by the state first? Thanks to the country, thanks to ms, thanks to the blog garden, thanks to the selfless xdjm, thank yourself......

The procedures for handling uncaught exceptions under asp. net are as follows:

(1) Create a class that implements the IHttpModule interface


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
namespace DotNet.Common.WebForm
{
  using DotNet.Common.Util;
  /// <summary>
  ///  General Uncaught Exception Handling  
  /// </summary>
  public class AspNetUnhandledExceptionModule : IHttpModule
  {
    static object syncObj = new object();
    static bool isInit = false;
    public AspNetUnhandledExceptionModule()
    {
    }
    #region IHttpModule Methods
    public void Init(HttpApplication context)
    {
      lock (syncObj)
      {
        if (!isInit)
        {
          AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
          isInit = true;
        }
      }
    }
    public void Dispose()
    {
    }
    #endregion
    #region OnUnhandledException
    void OnUnhandledException(object o, UnhandledExceptionEventArgs e)
    {
      if (e.ExceptionObject == null) return;
      Exception ex = e.ExceptionObject as Exception;
      string error = string.Format(" How to throw an exception: {0}\n Error message: {1}\n Error stack: {2}\n",
              ex.TargetSite, ex.Message, ex.StackTrace);
      Logger.WriteFileLog(error, AppDomain.CurrentDomain.BaseDirectory + "LogFile");
    }
    #endregion
  }
}

(2), web. config node configuration


<httpModules>
   <add name="AspNetUnhandledExceptionModule" type="DotNet.Common.WebForm.AspNetUnhandledExceptionModule, DotNet.Common.WebForm"></add>
</httpModules>

Finally, post the test code:


protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Test), null);
  }
}
protected void Test(object state)
{
  int[] numArr = new int[100];
  numArr[100] = 100; // Anomaly 
}

It should be noted that when an exception occurs in a program handled by a thread or thread pool, each thread will have its own independent context, so the HttpContext object should appear as little as possible in the exception handling stage.

Summary: I don't know how many children think exception handling is to throw an exception and finish it under try... catch1 in the code. If there is, hehe, the building pig took "no one is born with 10 all 10 beautiful" this sentence to comfort themselves. Of course, try... catch is not impossible, which only shows that our attitude towards anomalies is too hasty. In order to show our professionalism and comprehensiveness, please refer to other professional articles on exception handling to study once. Compared with the core idea of exception handling ("great wisdom" of exception handling), the summary of this article ("small skills" of exception handling) may also be misleading for beginners, so please pay attention to screening.

Complete example code code click here to download this site.

I hope this paper is helpful to everyone's asp. net programming.


Related articles: