Website-level exception capture in Asp.net

Recently, in a management system of a company, some independent modules have been used. In the implementation of these classes, errors are thrown directly. I think this is our usual practice. However, the problem also came, because I did not catch these exceptions in the Asp.net page, and these classes were used in many pages, so unfriendly error messages would appear on multiple pages.

How to do? I don't want to modify the code one by one, which is time-consuming and labor-intensive, so that programming will not become manual labor, thus losing the fun. This reminded me of custom error pages, so Google finally found the answer.

1. Configure web.config:

< customErrors  mode ="RemoteOnly"  defaultRedirect ="ErrorPage.aspx"  redirectMode ="ResponseRewrite" />
 The key is the redirectMode attribute, which defaults to ResponseRedirect. Since it is redirected, the exception is ignored, so you cannot catch the exception . Here's a wordy sentence: because before and after the error is considered to be two requests, we know that the http protocol is a stateless protocol, and it is not surprising that the second request ignores the first exception. So someone uses Session or Application to save exceptions, which is not desirable. The correct way is to use "ResponseRewrite".

2. Output abnormal information:

 We know that when the website fails, it will automatically lead to our ErrorPage.apx page. How to access this exception in ErrorPage.aspx? The answer is: Server.GetLastError(), of course it may be Server.GetLastError(). InnerException . This needs to be analyzed in detail.

if (Server.GetLastError() != null ){    Response.Write(Server.GetLastError().Message);}

By the way:

Asp.net MVC is much simpler, the framework comes with an Error.aspx, the exception is stored in Model.Exception, and Web.config is also configured for us.

The web pages developed since last year are basically MVC, with clear structure, easy expansion, and cool HTML code output. It's helpful to have a look at the MVC source code when you have time.

Reprinted in: https://www.cnblogs.com/zhangchenliang/archive/2011/04/19/2021257.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324110461&siteId=291194637