網站首頁 編程語言 正文
我們平常在程序里面為了捕獲異常,會加上try-catch-finally代碼,但是這樣會使得程序代碼看起來很龐大,在MVC中我們可以使用異常過濾器來捕獲程序中的異常,如下圖所示:
使用了異常過濾器以后,我們就不需要在Action方法里面寫Try -Catch-Finally這樣的異常處理代碼了,而把這份工作交給HandleError去做,這個特性同樣可以應用到Controller上面,也可以應用到Action方面上面。
注意:
使用異常過濾器的時候,customErrors配置節屬性mode的值,必須為On。
演示示例:
1、Error控制器代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; using System.IO; namespace _3_異常過濾器.Controllers { public class ErrorController : Controller { // GET: Error [HandleError(ExceptionType =typeof(ArithmeticException),View ="Error")] public ActionResult Index(int a,int b) { int c = a / b; ViewData["Result"] = c; return View(); } ////// 測試數據庫異常 /// ///[HandleError(ExceptionType = typeof(SqlException), View = "Error")] public ActionResult DbError() { // 錯誤的連接字符串 SqlConnection conn = new SqlConnection(@"Initial Catalog=StudentSystem; Integrated Security=False;User Id=sa;Password=******;Data Source=127.0.0.1"); conn.Open(); // 返回Index視圖 return View("Index"); } /// /// IO異常 /// ///[HandleError(ExceptionType = typeof(IOException), View = "Error")] public ActionResult IOError() { // 訪問一個不存在的文件 System.IO.File.Open(@"D:\error.txt",System.IO.FileMode.Open); // 返回Index視圖 return View("Index"); } } }
2、路由配置如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace _3_異常過濾器 { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); // 新增路由配置 routes.MapRoute( name: "Default2", url: "{controller}/{action}/{a}/{b}", defaults: new { controller = "Home", action = "Index", a=0,b=0 } ); } } }
3、配置文件如下:
4、運行結果
URL:http://localhost:21868/error/index/8/4
結果:
URL:http://localhost:21868/error/index/8/0
結果:
URL:http://localhost:21868/error/DbError
結果:
URL:http://localhost:21868/error/IOError
結果:
在同一個控制器或Action方法上可以通過HandleError處理多個異常,通過Order屬性決定捕獲的先后順序,但最上面的異常必須是下面異常的同類級別或子類。如下圖所示:
上面的程序可以修改成如下的代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; using System.IO; namespace _3_異常過濾器.Controllers { [HandleError(Order =1, ExceptionType = typeof(SqlException), View = "Error")] [HandleError(Order =2, ExceptionType = typeof(IOException), View = "Error")] [HandleError(Order =3)] //不指定View,默認跳轉到Share下面的Error視圖 public class ErrorController : Controller { public ActionResult Index(int a,int b) { int c = a / b; ViewData["Result"] = c; return View(); } ////// 測試數據庫異常 /// ///public ActionResult DbError() { // 錯誤的連接字符串 SqlConnection conn = new SqlConnection(@"Initial Catalog=StudentSystem; Integrated Security=False;User Id=sa;Password=******;Data Source=127.0.0.1"); conn.Open(); // 返回Index視圖 return View("Index"); } /// /// IO異常 /// ///public ActionResult IOError() { // 訪問一個不存在的文件 System.IO.File.Open(@"D:\error.txt",System.IO.FileMode.Open); // 返回Index視圖 return View("Index"); } } }
在上面的示例中,捕獲異常的時候只是跳轉到了Error視圖,如果我們想獲取異常的具體信息該怎么辦呢?如下圖所示:
查看MVC源碼,可以發現HandleError返回的是HandleErrorInfo類型的model,利用該model可以獲取異常的具體信息,修改Error視圖頁面如下:
結果:
原文鏈接:https://www.cnblogs.com/dotnet261010/p/9005952.html
相關推薦
- 2022-10-20 C++?float、double判斷是否等于0問題_C 語言
- 2022-12-26 Python常用標準庫之os模塊功能_python
- 2022-07-18 Nio中Buffer的Scattering和Gathering
- 2022-09-30 python實現圖像邊緣檢測_python
- 2023-07-29 el-tree 只展示選中值
- 2023-01-02 C語言中getchar(?)?函數使用詳解_C 語言
- 2022-10-11 React - 當輸入框獲取焦點時自動選中輸入框中的內容
- 2024-01-28 spring ioc容器
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支