MVC Tutorial IX: Exception filters

Source: Internet
Author: User

We usually add try-catch-finally code in order to catch exceptions in the program, but this makes the program code look huge, and in MVC we can use exception filters to catch exceptions in the program, as shown in:

Using the exception filter, we do not need to write in the action method try-catch-finally such exception processing code, and the job to HandleError to do, this feature can also be applied to the controller, can also be applied to the action aspect above.

Attention:

When using an exception filter, the value of the CustomErrors configuration section property mode must be on.

Demo Example:

1. The error controller code is as follows:

1 using System;2 using System.Collections.Generic;3 using System.Linq;4 using System.Web;5 using SYSTEM.WEB.MVC;6 using System.Data.SqlClient;7 using System.IO;8 9 namespace _3_ exception filter. ControllersTen { One Public class Errorcontroller:controller A     { - //Get:error - [HandleError (Exceptiontype =typeof (arithmeticexception), View = "Error")] the Public actionresult Index (int a,int b) -         { - int c = A/b; - viewdata["Result"] = C; + return View (); -         } +  A///<Summary> at /// Test Database Exception -///</Summary> -///<returns></returns> - [HandleError (Exceptiontype = typeof (SqlException), View = "Error")] - Public ActionResult Dberror () -         { in //Bad connection string - SqlConnection conn = new SqlConnection (@ "Initial Catalog=studentsystem; Integrated Security=false; User Id=sa; password=******;D ata source=127.0.0.1 "); to Conn. Open (); + //Return to Index view - return View ("Index"); the         } *  $///<Summary>Panax Notoginseng // IO exception -///</Summary> the///<returns></returns> + [HandleError (Exceptiontype = typeof (IOException), View = "Error")] A Public ActionResult IOError () the         { + //access to a nonexistent file - System.IO.File.Open (@ "D:\error.txt", System.IO.FileMode.Open); $ //Return to Index view $ return View ("Index"); -         } -     } the}

2. The routing configuration is as follows:

1 using System;2 using System.Collections.Generic;3 using System.Linq;4 using System.Web;5 using SYSTEM.WEB.MVC;6 using System.Web.Routing;7 8 namespace _3_ anomaly Filter9 {Ten Public class Routeconfig One     { A Public static void RegisterRoutes (RouteCollection routes) -         { - routes. Ignoreroute ("{resource}.axd/{*pathinfo}"); the  - routes. MapRoute ( - Name: "Default", - URL: "{controller}/{action}/{id}", + defaults:new {controller = "Home", action = "Index", id = urlparameter.optional} -             ); +  A //New routing configuration at routes. MapRoute ( - Name: "Default2", - URL: "{controller}/{action}/{a}/{b}", - defaults:new {controller = "Home", action = "Index", a=0,b=0} -           ); -         } in     } -}

3. The configuration file is as follows:

<system.web>    <compilation debug= "true" targetframework= "4.6.1"/>    

4. Operation result

Url:http://localhost:21868/error/index/8/4

Results:

url:http://localhost:21868/error/index/8/0

Results:

Url:http://localhost:21868/error/dberror

Results:

Url:http://localhost:21868/error/ioerror

Results:

Multiple exceptions can be handled by HandleError on the same controller or action method, with the order attribute determining the order of the captures, but the topmost exception must be the same level or subclass of the following exception. As shown in the following:

The above program can be modified to the following code:

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingsystem.web;5 usingSYSTEM.WEB.MVC;6 usingSystem.Data.SqlClient;7 usingSystem.IO;8 9 namespace_3_ exception filter. ControllersTen { One[HandleError (Order =1, Exceptiontype =typeof(SqlException), View ="Error")] A[HandleError (Order =2, Exceptiontype =typeof(IOException), View ="Error")] -[HandleError (Order =3)]//does not specify a view, the default jumps to the error view under Share -      Public classErrorcontroller:controller the     { -          PublicActionResult Index (intAintb) -         { -             intc = A/b; +viewdata["Result"] =C; -             returnView (); +         } A  at         /// <summary> -         ///Test Database Exceptions -         /// </summary> -         /// <returns></returns> -          Publicactionresult dberror () -         { in             //the wrong connection string -SqlConnection conn =NewSqlConnection (@"Initial Catalog=studentsystem; Integrated Security=false; User Id=sa; password=******;D ata source=127.0.0.1"); to Conn. Open (); +             //return to Index view -             returnView ("Index"); the         } *  $         /// <summary>Panax Notoginseng         ///IO Exception -         /// </summary> the         /// <returns></returns> +          Publicactionresult IOError () A         { the             //accessing a file that does not exist +System.IO.File.Open (@"D:\error.txt", System.IO.FileMode.Open); -             //return to Index view $             returnView ("Index"); $         } -     } -}

In the above example, when the exception was caught, it just jumps to the error view, what if we want to get the specific information for the exception? As shown in the following:

View MVC source code, you can find that HandleError returned is the model of the Handleerrorinfo type, using the model can get the specific information of the exception, modify the error view page as follows:

@model handleerrorinfo<! DOCTYPE html>

Results:

MVC Tutorial IX: Exception filters

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.