using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Filter.Filters { using System.Web.Mvc; public class ExpAttribute:HandleErrorAttribute { /// <summary> /// 用于截获当前action逻辑代码执行的异常,但是此异常没有被程序员通过try{} catch{}处理 /// </summary> /// <param name="filterContext"></param> public override void OnException(ExceptionContext filterContext) { //filterContext.Exception.Message 获取描述当前异常信息 //filterContext.Exception.InnerException 获取导致当前异常的system.Exception实例 /* 日志文件: 优点:快; 确定:不容易查找和统计 * 数据库:能够很好地进行统计 * LogNet4.dll :.net中开源的日志记录模块,可以实现向文本和数据库中记录日志 */ //模拟写日志,但是有很大弊端,不建议使用在项目中 string phyPath = filterContext.HttpContext.Server.MapPath("/log.txt"); //获取异常对象 string err = filterContext.Exception.ToString(); //具体的异常内容 string errfmt = string.Format("{0}===============>{1}\r\n", DateTime.Now.ToString(), err); //将指定字符串 追加到 指定路径的文件 System.IO.File.AppendAllText(phyPath, "" + errfmt); //告诉MVC框架此异常已经处理,不需要将错误信息响应给用户 filterContext.ExceptionHandled = false; base.OnException(filterContext); } } }