ASP. net mvc custom exception handling and mvc Exception Handling

Source: Internet
Author: User

ASP. net mvc custom exception handling and mvc Exception Handling

1. Custom Exception Handling filter files

Create a MyExceptionAttribute. cs exception handling file

The MyExceptionAttribute. cs code is as follows:

Using System; using System. collections. generic; using System. linq; using System. web; using System. web. mvc; namespace WebApp. models {public class MyExceptionAttribute: HandleErrorAttribute {public static Queue <Exception> exceptionQueue = new Queue <Exception> (); // Exception Handling queue object // <summary> // exception occurs in the Controller method, this method is called to capture exceptions. // </summary> // <param name = "filterContext"> </param> public override void OnException (ExceptionContext filterContext) {exceptionQueue. enqueue (filterContext. exception); // write the caught Exception information to filterContext in the queue. httpContext. response. redirect ("/Error.html"); // jump to the error page base. onException (filterContext );}}}

 

2. Change the error handling filter to a custom exception handling filter.

Modify as follows:

Using System. web; using System. web. mvc; using WebApp. models; namespace WebApp {public class FilterConfig {public static void RegisterGlobalFilters (GlobalFilterCollection filters) {// filters. add (new handleerrorattriters (); filters. add (new MyExceptionAttribute (); // use a filter for custom exception handling }}}

 

3. Modify the Global. asax file. When the program is loaded for the first time, enable the thread scan exception queue to process exception information.

Using Spring. web. mvc; using System. collections. generic; using System. IO; using System. linq; using System. text; using System. threading; using System. web; using System. web. http; using System. web. mvc; using System. web. optimization; using System. web. routing; using WebApp. models; namespace WebApp {// Note: For instructions on enabling the IIS6 or IIS7 Classic mode, // visit http://go.microsoft.com/?LinkId=9394801 Public class MvcApplication: SpringMvcApplication // System. web. httpApplication {protected void Application_Start () {AreaRegistration. registerAllAreas (); WebApiConfig. register (GlobalConfiguration. configuration); FilterConfig. registerGlobalFilters (GlobalFilters. filters); RouteConfig. registerRoutes (RouteTable. routes); BundleConfig. registerBundles (BundleTable. bundles); # region enables threads to scan different queues and handle exception information strin G fileLogPath = Server. mapPath ("/Log/"); // knows the folder path used to save the Error Log File // enables a thread to scan the Log queue ThreadPool. unsafeQueueUserWorkItem (a) =>{ while (true) {if (MyExceptionAttribute. predictionqueue. count> 0) // checks whether data exists in the queue {Exception ex = MyExceptionAttribute. predictionqueue. dequeue (); // if (ex! = Null) {string fileName = DateTime. now. toString ("yyyy-MM-dd") + ". txt "; File. appendAllText (fileLogPath + fileName, ex. toString (), Encoding. default); // append an exception to the file} else {Thread. sleep (3000) ;}} else {Thread. sleep (3000); // if there is no data in the queue, let the current thread rest for 3 seconds to avoid CPU idling and CPU waste}, fileLogPath ); # endregion }}}

 

4. test:

   public ActionResult Index()        {            int a = 2;            int b = 0;            int c = a / b;            return Content(c.ToString());        }

 

5. Results

 

6. other instructions:

1. Solve the log problem of high concurrency errors:
1.1 Use the traditional lock method. If the concurrency is large, the user will be stuck.
. Open a queue on the server, store user error information, and enable a thread to process it separately. (The queue is in the memory and the write speed is very fast)
This is the producer consumer model.

2. The Application_Start () method in Global is called only when the program is executed for the first time.

3. ThreadPool the thread pool has good performance, which is much more efficient than creating a thread by ourselves.

4. The pool is used to solve the problem of frequent object creation, and frequent creation consumes performance.

5. Queue is thread-safe. It processes multiple threads internally without any concurrency issues.

 

7. Download source code:

Click to download>

 

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.