need to set filtercontext.result=new redirectresult('linkcustompage');

done. so...

ASP.NET MVC异常处理模块详解

作者:我是攻城狮 字体:[增加 减小] 类型:转载 时间:2016-03-17 我要评论
这篇文章主要为大家详细介绍了ASP.NET MVC异常处理模块,对异常处理感兴趣的小伙伴们可以参考一下
一、前言
  异常处理是每个系统必不可少的一个重要部分,它可以让我们的程序在发生错误时友好地提示、记录错误信息,更重要的是不破坏正常的数据和影响系统运行。异常处理应该是一个横切点,所谓横切点就是各个部分都会使用到它,无论是分层中的哪一个层,还是具体的哪个业务逻辑模块,所关注的都是一样的。所以,横切关注点我们会统一在一个地方进行处理。无论是MVC还是WebForm都提供了这样实现,让我们可以集中处理异常。
  在MVC中,在FilterConfig中,已经默认帮我们注册了一个HandleErrorAttribute,这是一个过滤器,它继承了FilterAttribute类和实现了IExceptionFilter接口。说到异常处理,马上就会联想到500错误页面、记录日志等,HandleErrorAttribute可以轻松的定制错误页,默认就是Error页面;而记录日志我们也只需要继承它,并替换它注册到GlobalFilterCollection即可。关于HandleErrorAttribute很多人都知道怎么使用了,这里就不做介绍了。
  ok,开始进入主题!在MVC中处理异常,相信开始很多人都是继承HandleErrorAttribute,然后重写OnException方法,加入自己的逻辑,例如将异常信息写入日志文件等。当然,这并没有任何不妥,但良好的设计应该是场景驱动的,是动态和可配置的。例如,在场景一种,我们希望ExceptionA显示错误页面A,而在场景二中,我们希望它显示的是错误页面B,这里的场景可能是跨项目了,也可能是在同一个系统的不同模块。另外,异常也可能是分级别的,例如ExceptionA发生时,我们只需要简单的恢复状态,程序可以继续运行,ExceptionB发生时,我们希望将它记录到文件或者系统日志,而ExceptionC发生时,是个较严重的错误,我们希望程序发生邮件或者短信通知。简单地说,不同的场景有不同的需求,而我们的程序需要更好的面对变化。当然,继承HandleErrorAttribute也完全可以实现上面所说的,只不过这里我不打算去扩展它,而是重新编写一个模块,并且可以与原有的HandleErrorAttribute共同使用。
二、设计及实现
2.1 定义配置信息
  从上面已经可以知道我们要做的事了,针对不同的异常,我们希望可以配置它的处理程序,错误页等。如下一个配置:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!--自定义异常配置-->
<settingException>
<exceptions>
<!--add优先级高于group-->
<add exception="Exceptions.PasswordErrorException"
view ="PasswordErrorView"
handler="ExceptionHandlers.PasswordErrorExceptionHandler"/>
<groups>
<!--group可以配置一种异常的view和handler-->
<group view="EmptyErrorView" handler="ExceptionHandlers.EmptyExceptionHandler">
<add exception="Exceptions.UserNameEmptyException"/>
<add exception="Exceptions.EmailEmptyException"/>
</group>
</groups>
</exceptions>
</settingException>
  其中,add 节点用于增加具体的异常,它的 exception 属性是必须的,而view表示错误页,handler表示具体处理程序,如果view和handler都没有,异常将交给默认的HandleErrorAttribute处理。而group节点用于分组,例如上面的UserNameEmptyException和EmailEmptyException对应同一个处理程序和视图。
  程序会反射读取这个配置信息,并创建相应的对象。我们把这个配置文件放到Web.config中,保证它可以随时改随时生效。
2.2 异常信息包装对象
  这里我们定义一个实体对象,对应上面的节点。如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ExceptionConfig
{
/// <summary>
/// 视图
/// </summary>
public string View{get;set;} /// <summary>
/// 异常对象
/// </summary>
public Exception Exception{get;set;} /// <summary>
/// 异常处理程序
/// </summary>
public IExceptionHandler Handler{get;set;}
}
2.3 定义Handler接口
  上面我们说到,不同异常可能需要不同处理方式。这里我们设计一个接口如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
public interface IExceptionHandler
{
/// <summary>
/// 异常是否处理完成
/// </summary>
bool HasHandled{get;set;} /// <summary>
/// 处理异常
/// </summary>
/// <param name="ex"></param>
void Handle(Exception ex);
}
  各种异常处理程序只要实现该接口即可。
2.3 实现IExceptionFilter
  这是必须的。如下,实现IExceptionFilter接口,SettingExceptionProvider会根据异常对象类型从配置信息(缓存)获取包装对象。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class SettingHandleErrorFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if(filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
ExceptionConfig config = SettingExceptionProvider.Container[filterContext.Exception.GetType()];
if(config == null)
{
return;
}
if(config.Handler != null)
{
//执行Handle方法
config.Handler.Handle(filterContext.Exception);
if (config.Handler.HasHandled)
{
//异常已处理,不需要后续操作
filterContext.ExceptionHandled = true;
return;
}
}
//否则,如果有定制页面,则显示
if(!string.IsNullOrEmpty(config.View))
{
//这里还可以扩展成实现IView的视图
ViewResult view = new ViewResult();
view.ViewName = config.View;
filterContext.Result = view;
filterContext.ExceptionHandled = true;
return;
}
//否则将异常继续传递
}
}
2.4 读取配置文件,创建异常信息包装对象
  这部分代码比较多,事实上,你只要知道它是在读取web.config的自定义配置节点即可。SettingExceptionProvider用于提供容器对象。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class SettingExceptionProvider
{
public static Dictionary<Type, ExceptionConfig> Container =
new Dictionary<Type, ExceptionConfig>(); static SettingExceptionProvider()
{
InitContainer();
} //读取配置信息,初始化容器
private static void InitContainer()
{
var section = WebConfigurationManager.GetSection("settingException") as SettingExceptionSection;
if(section == null)
{
return;
}
InitFromGroups(section.Exceptions.Groups);
InitFromAddCollection(section.Exceptions.AddCollection);
} private static void InitFromGroups(GroupCollection groups)
{
foreach (var group in groups.Cast<GroupElement>())
{
ExceptionConfig config = new ExceptionConfig();
config.View = group.View;
config.Handler = CreateHandler(group.Handler);
foreach(var item in group.AddCollection.Cast<AddElement>())
{
Exception ex = CreateException(item.Exception);
config.Exception = ex;
Container[ex.GetType()] = config;
}
}
} private static void InitFromAddCollection(AddCollection collection)
{
foreach(var item in collection.Cast<AddElement>())
{
ExceptionConfig config = new ExceptionConfig();
config.View = item.View;
config.Handler = CreateHandler(item.Handler);
config.Exception = CreateException(item.Exception);
Container[config.Exception.GetType()] = config;
}
} //根据完全限定名创建IExceptionHandler对象
private static IExceptionHandler CreateHandler(string fullName)
{
if(string.IsNullOrEmpty(fullName))
{
return null;
}
Type type = Type.GetType(fullName);
return Activator.CreateInstance(type) as IExceptionHandler;
} //根据完全限定名创建Exception对象
private static Exception CreateException(string fullName)
{
if(string.IsNullOrEmpty(fullName))
{
return null;
}
Type type = Type.GetType(fullName);
return Activator.CreateInstance(type) as Exception;
}
}
  以下是各个配置节点的信息:
  settingExceptions节点:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/// <summary>
/// settingExceptions节点
/// </summary>
public class SettingExceptionSection : ConfigurationSection
{
[ConfigurationProperty("exceptions",IsRequired=true)]
public ExceptionsElement Exceptions
{
get
{
return (ExceptionsElement)base["exceptions"];
}
}
}
  exceptions节点:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/// <summary>
/// exceptions节点
/// </summary>
public class ExceptionsElement : ConfigurationElement
{
private static readonly ConfigurationProperty _addProperty =
new ConfigurationProperty("", typeof(AddCollection), null, ConfigurationPropertyOptions.IsDefaultCollection); [ConfigurationProperty("", IsDefaultCollection = true)]
public AddCollection AddCollection
{
get
{
return (AddCollection)base[_addProperty];
}
} [ConfigurationProperty("groups")]
public GroupCollection Groups
{
get
{
return (GroupCollection)base["groups"];
}
}
}
  Group节点集:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/// <summary>
/// group节点集
/// </summary>
[ConfigurationCollection(typeof(GroupElement),AddItemName="group")]
public class GroupCollection : ConfigurationElementCollection
{
/*override*/ protected override ConfigurationElement CreateNewElement()
{
return new GroupElement();
} protected override object GetElementKey(ConfigurationElement element)
{
return element;
}
}
  group节点:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/// <summary>
/// group节点
/// </summary>
public class GroupElement : ConfigurationElement
{
private static readonly ConfigurationProperty _addProperty =
new ConfigurationProperty("", typeof(AddCollection), null, ConfigurationPropertyOptions.IsDefaultCollection); [ConfigurationProperty("view")]
public string View
{
get
{
return base["view"].ToString();
}
} [ConfigurationProperty("handler")]
public string Handler
{
get
{
return base["handler"].ToString();
}
} [ConfigurationProperty("", IsDefaultCollection = true)]
public AddCollection AddCollection
{
get
{
return (AddCollection)base[_addProperty];
}
}
}
  add节点集:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/// <summary>
/// add节点集
/// </summary>
public class AddCollection : ConfigurationElementCollection
{
/*override*/ protected override ConfigurationElement CreateNewElement()
{
return new AddElement();
} protected override object GetElementKey(ConfigurationElement element)
{
return element;
}
}
  add节点:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/// <summary>
/// add节点
/// </summary>
public class AddElement : ConfigurationElement
{
[ConfigurationProperty("view")]
public string View
{
get
{
return base["view"] as string;
}
} [ConfigurationProperty("handler")]
public string Handler
{
get
{
return base["handler"] as string;
}
} [ConfigurationProperty("exception", IsRequired = true)]
public string Exception
{
get
{
return base["exception"] as string;
}
}
}
三、测试
  ok,下面测试一下,首先要在FilterConfig的RegisterGlobalFilters方法中在,HandlerErrorAttribute前注册我们的过滤器:
  filters.Add(new SettingHandleErrorFilter())。
3.1 准备异常对象
   准备几个简单的异常对象:
?
1
2
3
public class PasswordErrorException : Exception{}
public class UserNameEmptyException : Exception{}
public class EmailEmptyException : Exception{}
3.2 准备Handler
  针对上面的异常,我们准备两个Handler,一个处理密码错误异常,一个处理空异常。这里没有实际处理代码,具体怎么处理,应该结合具体业务了。如:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class PasswordErrorExceptionHandler : IExceptionHandler
{
public bool HasHandled{get;set;} public void Handle(Exception ex)
{
//具体处理逻辑...
}
} public class EmptyExceptionHandler : IExceptionHandler
{
public bool HasHandled { get; set; } public void Handle(Exception ex)
{
//具体处理逻辑...
}
}
3.3 抛出异常
  按照上面的配置,我们在Action中手动throw异常
?
1
2
3
4
5
6
7
8
9
10
11
12
public ActionResult Index()
{
throw new PasswordErrorException();
}
public ActionResult Index2()
{
throw new UserNameEmptyException();
}
public ActionResult Index3()
{
throw new EmailEmptyException();
}
  可以看到,相应的Handler会被执行,浏览器也会出现我们配置的错误页面。
四、总结
  事实上这只是一个比较简单的例子,所以我称它为简单的模块,而是用框架、库之类的词。当然我们可以根据实际情况对它进行扩展和优化。微软企业库视乎也集成这样的模块,有兴趣的朋友可以了解一下

.net mvc onexception capture; redirectresult;的更多相关文章

  1. 了解ASP.NET MVC几种ActionResult的本质:HttpStatusCodeResult & RedirectResult/RedirectToRouteResult

    在本系列的最后一篇,我们来讨论最后三个ActionResult:HttpStatusCodeResult.RedirectResult和RedirectToRouteResult .第一个用于实现针对 ...

  2. System.Web.Mvc.RedirectResult.cs

    ylbtech-System.Web.Mvc.RedirectResult.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Culture=neutral, Pub ...

  3. MVC Controller return 格式之JsonResult、ContentResult、RedirectResult……

      //语法 public class JsonResult : ActionResult public class ContentResult : ActionResult public class ...

  4. MVC Ajax调用Action时-OnActionExecuting RedirectResult 无法跳转的处理办法

    public class BaseController : Controller { protected override void OnActionExecuting(ActionExecuting ...

  5. MVC常遇见的几个场景代码分享

    本次主要分享几个场景的处理代码,有更好处理方式多多交流,相互促进进步:代码由来主要是这几天使用前端Ace框架做后台管理系统,这Ace是H5框架里面的控件效果挺多的,做兼容也很好,有点遗憾是控件效果基本 ...

  6. ASP.NET MVC项目实践技巧

    原创文章转载请注明出处:@协思, http://zeeman.cnblogs.com 在.NET开发初期,微软提供的WEB开发模型是WebForm,试图消除Web和桌面的隔阂,建立一致的开发体验.但是 ...

  7. [ASP.NET MVC 小牛之路]11 - Filter

    Filter(筛选器)是基于AOP(面向方面编程)的设计,它的作用是对MVC框架处理客户端请求注入额外的逻辑,以非常简单优美的方式实现横切关注点(Cross-cutting Concerns).横切关 ...

  8. ASP.NET MVC过滤器

    在ASP.NET MVC中有个重要特性就是过滤器,使得我们在MVC程序开发中更好的控制浏览器请求的URL,不是每个请求都有响应内容,只有特定得用户才有.园子里关于过滤器的资料也有很多,这篇文章主要是记 ...

  9. 16、ASP.NET MVC入门到精通——MVC过滤器

    本系列目录:ASP.NET MVC4入门到精通系列目录汇总 在ASP.NET MVC中有四种过滤器类型

随机推荐

  1. 递归函数的用法及array_merge的用法

    $info=M('navclass')->select(); function getAllArray($data, $pid =1) { $arr = array(); foreach ($d ...

  2. asp.net 操作Excel大全

    asp.net 操作Excel大全 转:http://www.cnblogs.com/zhangchenliang/archive/2011/07/21/2112430.html 我们在做excel资 ...

  3. (转)KeyDown、KeyUp、KeyPress区别

    Windows窗体通过引发键盘事件来处理键盘输入以响应Windows消息,大多数Windows窗体应用程序都通过处理键盘事件来以独占方式处理键盘输入. 1.按键的类型 Windows窗体将键盘输入标 ...

  4. C#向文本文件中写入日志

    今天看了一篇文章,说的是使用微软自带的日志类写日志,然后晚上我就花了2个多小时自己动手试了一下,然后模仿者自己封装了一个类库. 下面是自己封转的类: /***** * 创建人:金河 * 创建日期:20 ...

  5. javascrit2.0完全参考手册(第二版) 第2章第1节 基本定义

    在这里,我们介绍一些将要使用的编程语言术语.表2-1提供了精确定义的概念. Table 2-1: 编程语言的基本术语 名字 定义 例子 Token令牌 最小的不可分割的词汇的语言单位.一个连续的字符序 ...

  6. EasyUI组件(窗口组件)

    注意首先要在title后面导入配置文件,前后顺序不能乱 <!-- 1.jQuery的js包 --><script type="text/javascript" s ...

  7. 数位DP bzoj1026

    1026: [SCOI2009]windy数 Time Limit: 1 Sec  Memory Limit: 162 MBSubmit: 5809  Solved: 2589[Submit][Sta ...

  8. hdu A Bug's Life

    题目意思:给定一系列数对,例如a和b,表示a和b不是同一种性别,然后不断的给出这样的数对,问有没有性别不对的情况. 例如给定: 1    2 3    4 1    3 那这里就是说1和2不是同种性别 ...

  9. 【HDU1914 The Stable Marriage Problem】稳定婚姻问题

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1914 题目大意:问题大概是这样:有一个社团里有n个女生和n个男生,每位女生按照她的偏爱程度将男生排序, ...

  10. BizTalk动手实验(十二)WCF-Oracle适配器使用

    1 课程简介 通过本课程熟悉WCF-Oracle适配器的的使用 2 准备工作 1. 新建BizTalk空项目 2. 配置BizTalk项目的应用程序名称及程序签名. 3. Oracle数据库 ( Or ...