我们平常在程序里面为了捕获异常,会加上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教程九:异常过滤器的更多相关文章

  1. MVC教程:授权过滤器

    一.过滤器 过滤器(Filter)的出现使得我们可以在ASP.NET MVC程序里更好的控制浏览器请求过来的URL,并不是每个请求都会响应内容,只有那些有特定权限的用户才能响应特定的内容.过滤器理论上 ...

  2. ASP.NET MVC 过滤、异常过滤器

    记录下过滤器的学习—_— APS.NET MVC中的每一个请求,都会分配给相应的控制器和对应的行为方法去处理,而在这些处理的前后如果想再加一些额外的逻辑处理,这样会造成大量代码的重复使用,这不是我们希 ...

  3. 简明python教程九----异常

    使用try...except语句来处理异常.我们把通常的语句放在try-块中,而把错误处理语句放在except-块中. import sys try: s = raw_input('Enter som ...

  4. MVC异常日志生产者消费者模式记录(异常过滤器)

    生产者消费者模式 定义自己的异常过滤器并注册 namespace Eco.Web.App.Models { public class MyExceptionAttribute : HandleErro ...

  5. MVC 全局异常过滤器HandleErrorAttribute

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  6. asp.net core MVC 全局过滤器之ExceptionFilter异常过滤器(一)

    本系类将会讲解asp.net core MVC中的内置全局过滤器的使用,将分为以下章节 asp.net core MVC 过滤器之ExceptionFilter异常过滤器(一) asp.net cor ...

  7. 笨鸟先飞之ASP.NET MVC系列之过滤器(06异常过滤器)

    概念介绍 异常过滤器主要在我们方法中出现异常的时候触发,一般我们用 异常过滤器 记录日志,或者在产生异常时做友好的处理 如果我们需要创建异常过滤器需要实现IExceptionFilter接口. nam ...

  8. [Asp.net MVC]HandleErrorAttribute异常过滤器

    摘要 在asp.net mvc中除了使用try...catch/finally来处理异常外,它提供了一种通过在Controller或者Action上添加特性的方式来处理异常. HandleErrorA ...

  9. MVC与WebApi中的异常过滤器

    一.MVC的异常过滤器   1.自定义MVC异常过滤器 创建一个类,继承HandleErrorAttribute即可,如果不需要作为特性使用直接实现IExceptionFilter接口即可, 注意,该 ...

随机推荐

  1. QT creator 编辑器快捷键

    QT creator 编辑器快捷键 一.快捷键配置方法:   进入“工具->选项->环境->键盘”即可配置快捷键.     二.常用默认快捷键:       编号 快捷键 功能 1 ...

  2. unity, 2d rope

    https://www.youtube.com/watch?v=l6awvCT29yU

  3. JavaScript DOM API初步(整理)

    文档对象模型 文档对象模型(Doucment Object Model,DOM)是表示文档(如HTML文档.XML文档)和访问.操作构成文档的各种元素的应用程序接口.在DOM中,HTML文档的层次结构 ...

  4. Android 4.1的新特性介绍

    原文:http://android.eoe.cn/topic/summary 果冻豆 - Android 4.1 通知系统 - Notifications 在Android 4.1系统上通知的功能大大 ...

  5. Fiddlercore Demo - Fiddler

    public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Loa ...

  6. golang 解决 TCP 粘包问题

    什么是 TCP 粘包问题以及为什么会产生 TCP 粘包,本文不加讨论.本文使用 golang 的 bufio.Scanner 来实现自定义协议解包. 协议数据包定义 本文模拟一个日志服务器,该服务器接 ...

  7. 菜鸟学Java(十九)——WEB项目测试好帮手,Maven+Jetty

    做WEB开发,测试是一件很费时间的事情.所以我们就应该用更简单.更快捷的方式进行测试.今天就向大家介绍一个轻量级的容器——jetty.今天说的etty是Maven的一个插件jetty-maven-pl ...

  8. linux命令(50):comm命令的用法,求交集

    Linux comm命令 使用局限比较大,适用于特殊场合: Linux comm命令用于比较两个已排过序的文件. 排序:sort -u file 这项指令会一列列地比较两个已排序文件的差异,并将其结果 ...

  9. Asp.Net正则获取链接地址

    string html = “html代码”; Regex reg = new Regex(@"(?is)<a[^>]*?href=(['""]?)(?< ...

  10. ubuntu14.04 +nginx+php5-fpm

    一,安装Nginx apt-get install nginx 1,配置nginx nginx所有的配置在 /etc/nginx/nginx.conf中 nginx.conf配置里面包括了 inclu ...