MVC教程九:异常过滤器
我们平常在程序里面为了捕获异常,会加上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();
} /// <summary>
/// 测试数据库异常
/// </summary>
/// <returns></returns>
[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");
} /// <summary>
/// IO异常
/// </summary>
/// <returns></returns>
[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、配置文件如下:
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
<!--customErrors配置节mode的属性值必须为On-->
<customErrors mode="On">
</customErrors>
</system.web>
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 =, ExceptionType = typeof(SqlException), View = "Error")]
[HandleError(Order =, ExceptionType = typeof(IOException), View = "Error")]
[HandleError(Order =)] //不指定View,默认跳转到Share下面的Error视图
public class ErrorController : Controller
{
public ActionResult Index(int a,int b)
{
int c = a / b;
ViewData["Result"] = c;
return View();
} /// <summary>
/// 测试数据库异常
/// </summary>
/// <returns></returns>
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");
} /// <summary>
/// IO异常
/// </summary>
/// <returns></returns>
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视图页面如下:
@model HandleErrorInfo
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width" />
<title>错误</title>
<style type="text/css">
p{
color:red;
}
</style>
</head>
<body>
@*<hgroup>
<h1>错误。</h1>
<h2>处理你的请求时出错。</h2>
</hgroup>*@
<p>
抛错控制器:<b>@Model.ControllerName</b> 抛错方法:<b>@Model.ActionName</b> 抛错类型:<b>@Model.Exception.GetType()</b>
</p>
<p>
异常信息:@Model.Exception.Message
</p>
<p>
堆栈信息:@Model.Exception.StackTrace
</p>
</body>
</html>
结果:

MVC教程九:异常过滤器的更多相关文章
- MVC教程:授权过滤器
一.过滤器 过滤器(Filter)的出现使得我们可以在ASP.NET MVC程序里更好的控制浏览器请求过来的URL,并不是每个请求都会响应内容,只有那些有特定权限的用户才能响应特定的内容.过滤器理论上 ...
- ASP.NET MVC 过滤、异常过滤器
记录下过滤器的学习—_— APS.NET MVC中的每一个请求,都会分配给相应的控制器和对应的行为方法去处理,而在这些处理的前后如果想再加一些额外的逻辑处理,这样会造成大量代码的重复使用,这不是我们希 ...
- 简明python教程九----异常
使用try...except语句来处理异常.我们把通常的语句放在try-块中,而把错误处理语句放在except-块中. import sys try: s = raw_input('Enter som ...
- MVC异常日志生产者消费者模式记录(异常过滤器)
生产者消费者模式 定义自己的异常过滤器并注册 namespace Eco.Web.App.Models { public class MyExceptionAttribute : HandleErro ...
- MVC 全局异常过滤器HandleErrorAttribute
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- asp.net core MVC 全局过滤器之ExceptionFilter异常过滤器(一)
本系类将会讲解asp.net core MVC中的内置全局过滤器的使用,将分为以下章节 asp.net core MVC 过滤器之ExceptionFilter异常过滤器(一) asp.net cor ...
- 笨鸟先飞之ASP.NET MVC系列之过滤器(06异常过滤器)
概念介绍 异常过滤器主要在我们方法中出现异常的时候触发,一般我们用 异常过滤器 记录日志,或者在产生异常时做友好的处理 如果我们需要创建异常过滤器需要实现IExceptionFilter接口. nam ...
- [Asp.net MVC]HandleErrorAttribute异常过滤器
摘要 在asp.net mvc中除了使用try...catch/finally来处理异常外,它提供了一种通过在Controller或者Action上添加特性的方式来处理异常. HandleErrorA ...
- MVC与WebApi中的异常过滤器
一.MVC的异常过滤器 1.自定义MVC异常过滤器 创建一个类,继承HandleErrorAttribute即可,如果不需要作为特性使用直接实现IExceptionFilter接口即可, 注意,该 ...
随机推荐
- iOS常用RGB颜色的色值表
常用RGB颜色表 R G B 值 R G B 值 R G B 值 黑色 0 0 0 #000000 黄色 255 255 0 #FFFF00 浅灰蓝色 176 224 230 #B0E0E6 象牙黑 ...
- springcloud中概念辨析
1 什么是微服务? 微服务架构是一种架构模式或者一种架构风格,他提倡将单一应用程序划分成一组小的服务,每个服务运行在独立进程中,服务之间相互协调.相互配合.服务之间采用轻量级的通信机制(一般是基于HT ...
- logstash 的 配置文件
[root@--- etc]# cat test_front_console.conf input { beats { type => beats port => } } filter { ...
- Fiddler 抓取 app 网络请求数据
通过设置代理在同一个路由器下可以通过 Fiddler 实现抓取 app 的网络数据 步骤如下: 手机(Android ,iOS 都可以)和 PC 连到同一个路由器 对手机连接的 WIFI 设置代理,代 ...
- 什么是内联函数(inline function)
In C, we have used Macro function an optimized technique used by compiler to reduce the execution ti ...
- PHP文件锁定写入实例分享
PHP文件锁定写入实例解析. 原文地址:http://www.jbxue.com/article/23118.html PHP文件写入方法,以应对多线程写入,具体代码: function file_w ...
- impress.js 一个创建在线幻灯的js库
真的好奇怪,我居然会写前端技术的博客.没有办法的,最近实习,看的大多是前端.所以今天就用这个来练练手了. Impress.js 是一个非常棒的用来创建在线演示的Javascript库.它基于CSS3转 ...
- Chrome浏览器在Windows 和 Linux下的键盘快捷方式
Windows 键盘快捷键 标签页和窗口快捷键 Ctrl+N 打开新窗口. Ctrl+T 打开新标签页. Ctrl+Shift+N 在隐身模式下打开新窗口. 按 Ctrl+O,然后选择文件. 通过 G ...
- python virtualenv使用
1.什么是virtualenv virtualenv用来做环境隔离,比如项目A使用了python2,项目B使用了python3 使用virtualenv可以分别生成项目A和项目B的环境包 2.virt ...
- (转)Windows7安装OpenSSH
(转自:http://blog.sina.com.cn/s/blog_4a0a8b5d01015b0n.html) OpenSSH很老了,所以... 最开始只是因为openSSH启动不了,才用的Mob ...