Summary of common public catch exception modes in ASP (source code)

Source: Internet
Author: User
Tags dotnet

In this paper, we summarize the common methods of public catch anomaly in ASP. Share to everyone for your reference, as follows:

In the actual development process, for an application system, should have its own set of mature exception processing framework, so when the exception occurs, can also get a unified processing style, the exception information gracefully feedback to developers and users. As we all know, the exception handling of. NET is thrown from the bottom to the top level in the form of an "exception chain", and if you cannot judge the boundary of an exception and catch an exception as early as possible, the CLR automatically handles it, but the overhead of the system is very large, so an important principle of exception handling is " Early detection of early-throw early processing ". However, the service-side common catch exception processing summarized in this paper can be broadly regarded as an operation in the performance layer, to capture specific exceptions for a particular layer, not within the scope of the discussion.

1, BasePage class processing method

Overrides the OnError event in the common base class of the page. In the previous "ASP. NET implementation of very useful custom page base class", Lou Pig has been posted code, it will no longer bother. According to experience, many people write almost all the time when developing, and it is very helpful for debugging and maintenance. It should be explained that each new page, its corresponding class must inherit from the BasePage class exception handling to function.

2, Global.asax treatment method

As described in 1, the exception handling of the BasePage class requires that each ASPX class file inherit it, and the applicability and performance will obviously be compromised. While the Global.asax file defines the methods, properties, and events common to all application objects in an ASP. NET application, we can implement Application_ in Global.asax without using basepage processing. Error events can also be handled. The following mimics the handling exception method in the BasePage class, implemented as follows:

?
12345678910111213141516171819202122232425262728293031323334 /// <summary>/// 出错处理:写日志,导航到公共出错页面/// </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>/// 处理异常,用来将主要异常信息写入文本日志/// </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引发异常的方法:{1}\n错误信息:{2}\n错误堆栈:{3}\n",    this.Request.RawUrl, ex.TargetSite, ex.Message, ex.StackTrace);  return error;}

The advantage of the above approach is that once the code is written, most of the exceptions that occur to your application are captured and processed. Lou Pig to be here sincerely feel, thank Ms for providing us with such an excellent framework, too easy.

3, IHttpModule interface processing

1 and 2 of the treatment of people are very familiar with, Lou Pig in the actual development is basically to follow the above two styles, and the building of the pig because of the size of the 2 of all-in-one treatment, and even already excited to thank Ms. However, when the ASP is called asynchronously, the exception thrown by a background thread or line constructor can not be fully captured by 1 or (and) 2, which involves the processing of an uncaught exception under ASP. In other words, the building pig has done a lot of large and small projects in the treatment of the exception is not complete. Is this a NC-building pig without first thanking the country for its consequences? Thank the country, thank MS, thanks to the blog Park, thanks to the selfless xdjm, thank you ...

The processing steps for an uncaught exception under ASP. NET are as follows:

(1), create a class that implements the IHttpModule interface

?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 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>  /// 通用未捕获异常处理   /// </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("引发异常的方法:{0}\n错误信息:{1}\n错误堆栈:{2}\n",              ex.TargetSite, ex.Message, ex.StackTrace);      Logger.WriteFileLog(error, AppDomain.CurrentDomain.BaseDirectory + "LogFile");    }    #endregion  }}

(2), Web. config node configuration

?
123 <httpModules>   <addname="AspNetUnhandledExceptionModule"type="DotNet.Common.WebForm.AspNetUnhandledExceptionModule, DotNet.Common.WebForm"></add></httpModules>

Finally post the test code:

?
123456789101112 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; //异常}

It is necessary to note that programs that are handled by threads or thread pools, when an exception occurs, each thread will have its own independent context, so the HttpContext object should appear as rarely as possible in the exception handling phase.

Summary: I do not know how many children's shoes think exception handling is in the code try...catch, throw an exception and then finished? If there is, hehe, that year the pig is to take "no one is born perfect" this sentence to comfort himself. Of course, Try...catch is not not, can only show that we treat the abnormal attitude is too hasty. In order to appear our professional and comprehensive, please refer to other exception handling professional article study, compared to the core idea of exception handling (Exception handling "big wisdom"), this article summarizes (Exception handling "Tips") may also be misleading for beginners, please be sure to pay attention to screening.

Full instance code code click here to download this site.

It is hoped that this article will help you with ASP.

Summary of common public catch exception modes in ASP (source code)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.