When writing a program, we occasionally fail to handle some exceptions due to negligence. If the exception details are prompted to the user, it will cause unsafe factors. If the details are not prompted, it will cause the user to report the exception. Although you can configure customErrors mode, only the administrator can view the error, but the problem may be found for a long time. With global exception handling, you can immediately record exceptions when exceptions occur, or directly send an email to the Administrator to report the exceptions as quickly as possible.
To add global exception handling for ASP. NET applications, the Error event of HttpApplication is added. This is similar to URL rewriting in the BeginRequest event. First, create a class that inherits System. Web. IHttpModule. Then add the Init method and the 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)
- {
- // Handle exceptions here
- }
- }
- }
Then you need to configure the httpModules of web. config to make it take effect.
My favorite practice now is to record the exception details in the database, return a number, and redirect the page to the error prompt page written by myself, send this number to the user. If you want to report an error, you only need to provide the error number. The administrator can find and modify the error details in the background.
The following describes two problems I encountered during global exception handling and my solutions.
The first is to obtain the abnormal hResult. Because the private attribute cannot be accessed directly, the solution is to obtain the result through (int) System. Runtime. InteropServices. Marshal. GetHRForException (exception ).
The second problem is to record many errors that are not caused by ASP. NET applications. For example, if you type an incorrect URL, the exception handling system records a "file does not exist ." But these error records not only do not really reflect the exceptions of ASP. NET applications, it will bring more trouble to the Administrator. My solution is to filter these httpexceptions by judging if (exception is System. Web. HttpException.
- Introduction to ASP. net mvc Framework
- Introduction to MvcAjaxPanel in ASP. NET MVC
- ASP. net mvc Framework to save UpdatePanel
- Use ASP. net mvc source code to find a solution
- ActionInvoker of ASP. net mvc Framework