Summary of common catch exception methods in asp.net development (with source code) _ Practical Skills

Source: Internet
Author: User
Tags dotnet error handling exception handling httpcontext

In this paper, we summarize the common catch exception methods in asp.net development. Share to everyone for your reference, specific as follows:

In the actual development process, for an application system, should have its own a set of mature exception handling framework, so that when the exception occurs, can also get a unified processing style, the exception information gracefully feedback to the developers and users. As we all know,. NET exception handling is the "exception chain" in the way from the bottom to the top level of the layer thrown, if the bounds of the exception are not judged as early as possible and the exception is caught, the CLR will automatically handle it, but the overhead of the system is very large, so an important principle of exception handling is " Early discovery had thrown early treatment. " However, the service-side common catch exception handling summarized in this article can be viewed broadly as an operation in the presentation layer, and it is not within the scope of the discussion to capture specific exceptions of a particular layer.

1, BasePage class processing mode

Rewrite the onerror event in the common base class of the page. In the front of this "asp.net implement very practical custom page base class", the building pig has pasted the code, no longer trouble. According to experience, many people write almost all the time, and it is helpful for debugging and maintenance. It should be explained that each new page, its corresponding class must inherit from the BasePage class exception processing to play a role.

2, Global.asax treatment mode

As described in 1, exception handling for the BasePage class requires that each ASPX class file inherit it, and the applicability and performance are clearly compromised. While the Global.asax file defines the methods, properties, and events that are common to all application objects in the ASP.net application, we can implement it in Global.asax without using the basepage approach Application_ Error events and processing can also be. The following simulates the handling of exception methods in the BasePage class, which is implemented as follows:

<summary>///error Handling: Write log, navigate to public error page///</summary>///<param name= "sender" ></param>///&LT;PA Ram 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>///handles exceptions to write primary exception information to the text log///</summary>///<param name= "ex" ></param>///<ret Urns></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 method that throws 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 approach is that you write code once, and most of the exceptions that occur with your application are captured and processed. Lou Pig to be here heartily to send a feeling, thanks to MS for providing us with such an excellent framework, too easy.

3, IHttpModule interface processing

1 and 2 of the treatment of all are very familiar with the actual development of the building pigs are basically followed by the above two methods, and the building pig because of the size of the 2 of this kind of treatment, and even excited to thank Ms. However, when the ASP.net program calls the thread for asynchronous processing, it is easy to occur in the background thread or line Cheng Chili thrown out of the exception can not be 1 or (and) 2 fully capture, which involves the asp.net under the unhandled exception processing. That is to say, a lot of the things that a pig has done before. The handling of exceptions is incomplete. This is the NC building pigs do not thank the country before the consequences of the plant? Thanks to the country, thanks to MS, thanks to the blog Park, thanks to the selfless xdjm, thank you ...

The processing steps for not catching 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 not catch 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 c Ontext) {Lock (syncobj) {if (!isinit) {APPDOMAIN.CURRENTDOMAIN.UNHANDLEDEXCEP
          tion + = new Unhandledexceptioneventhandler (onunhandledexception);
        Isinit = true; The public void Dispose () {} #endregion #region onunhandledexception void onunhandled
      Exception (Object o, UnhandledExceptionEventArgs e) {if (E.exceptionobject = null) return; ExCeption ex = e.exceptionobject as Exception; String error = String. Format ("method that throws 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

 
 

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; Exception
}

It should be explained that a program that is processed through threads or thread pools has its own separate context for each thread in the event of an exception, so the HttpContext object should appear as little as possible in the exception handling phase.

Summary: Do not know how many children shoes think that exception handling is in the code try...catch, throw an exception and then finished? If there is, oh, when the building pig is to take "no one is born perfect" this sentence to comfort their own. Of course, Try...catch is not not can not, only to show that we treat the abnormal attitude is too hasty. In order to appear to us professionally and comprehensively, please refer to other exception handling professional articles for study, compared to the core idea of exception handling ("Great wisdom" of exception handling), this article summarized (the "small skill" of exception handling) may also be misleading for beginners, please pay attention to the screening.

Full instance code code click here to download the site.

I hope this article will help you to ASP.net program design.

Related Article

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.