ASP.NET global exception handler


When we write the program occasionally inadvertently lead to some exceptions not treated. If Exception Details prompts the user to bring insecurity, if not prompted to give users more information and report abnormal trouble. Although the configuration can be achieved by customErrors mode only administrators can view the error, but found time problems may take longer. By global exception handler can immediately record an exception when an exception occurs, or send e-mail reports directly to the administrator to identify and handle exceptions at the fastest speed.

To add a global exception handler for ASP.NET applications mainly deal with Error adding event of the HttpApplication. This is similar to URL-rewrite method BeginRequest event. First built a succession System.Web.IHttpModule class. Then add the Init method and ShowError method.

namespace  Snowdream
{

    
public   class  HttpModule : System.Web.IHttpModule
    {

        
public   void  Init(System.Web.HttpApplication context)
        {
            context.Error 
+=   new  EventHandler(ShowError);

        }

        
private   void  ShowError( object  sender, EventArgs e)
        {

            
// 在这里进行异常处理

        }
    }
}

Then also you need to configure the web.config httpModules bring it into force.

I prefer the approach is the exception details recorded in the database, and then returns a number, and then redirect the page to write your own error page, this number will be presented to the user, the user only need to provide if you want to report an error the error number, the administrator will be able to find details about the error in the background and make changes.

Here's what I encountered two when making global exception handling problem and my solution

The first is to obtain an exception hResult, because it is private property can not be accessed directly, the solution is to get through (int) System.Runtime.InteropServices.Marshal.GetHRForException (exception)

The second problem is not due to record a lot of mistakes caused by ASP.NET applications, such as a user types a wrong URL, exception handling system will record a "file does not exist." Mistakes, and these mistakes can not really reflect not only records the ASP.NET application administrator exception but will bring more trouble. My solution is to filter these HttpException by determining if (exception is System.Web.HttpException).

Reproduced in: https: //www.cnblogs.com/zhangchenliang/archive/2011/04/11/2012817.html

Guess you like

Origin blog.csdn.net/weixin_34356138/article/details/93496055