MVC异常捕获处理,FilterConfig

MVC异常捕获处理,FilterConfig:

 public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new MyErrorAttribute());
        }
    }

    public class MyErrorAttribute : HandleErrorAttribute
    {
        public void LogException(ExceptionContext filterContext, ExceptionType exceptionType)
        {
            //var url = filterContext.RouteData.Values["controller"] + "/" + filterContext.RouteData.Values["action"];
            string exception = string.Empty;
            string data = string.Empty;
            string url = string.Empty;
            string message = string.Empty;
            string controllerName = string.Empty;
            string actionName = string.Empty;
            int userId = 0;
            try
            {
                if (filterContext.Exception.InnerException != null)
                {
                    exception = JsonConvert.SerializeObject(filterContext.Exception.InnerException, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
                }
                else
                {
                    exception = JsonConvert.SerializeObject(filterContext.Exception, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

                }

                string name = System.Web.HttpContext.Current.User.Identity.Name;
                UserTicket userTicket = new UserTicket();
                if (!string.IsNullOrEmpty(name))
                {
                    FormsIdentity id = (FormsIdentity)System.Web.HttpContext.Current.User.Identity;
                    FormsAuthenticationTicket ticket = id.Ticket;
                    userTicket = JsonHelper.ParseJSON<UserTicket>(id.Ticket.UserData);
                    #region 返回当前用户

                    userId = userTicket.UserId;

                    #endregion
                }

                url = JsonConvert.SerializeObject(filterContext.RequestContext.HttpContext.Request.Url);
                message = filterContext.Exception.Message;
                userId = userId; //filterContext.RequestContext.HttpContext.User.Identity.Name.ToInt32();
                controllerName = filterContext.Controller.ControllerContext.RouteData.Values["controller"].ToString();
                actionName = filterContext.Controller.ControllerContext.RouteData.Values["action"].ToString();
                var d = System.Web.HttpContext.Current.Request.InputStream;
                d.Position = 0;
                var postData = new StreamReader(d).ReadToEnd();
                var qdata = string.Empty;
                var fdata = string.Empty;
                for (int i = 0; i < filterContext.RequestContext.HttpContext.Request.Form.Count; i++)
                {
                    fdata += filterContext.RequestContext.HttpContext.Request.Form.Keys[i].ToString() + "=" + filterContext.RequestContext.HttpContext.Request.Form[i].ToString() + "&";
                }
                for (int i = 0; i < filterContext.RequestContext.HttpContext.Request.QueryString.Count; i++)
                {
                    qdata += filterContext.RequestContext.HttpContext.Request.QueryString.Keys[i].ToString() + "=" + filterContext.RequestContext.HttpContext.Request.QueryString[i].ToString() + "&";
                }
                var request = new
                {
                    Content = new
                    {
                        Query = qdata,
                        Form = fdata,
                        Body = postData
                    },
                    filterContext.RequestContext.HttpContext.Request.Headers,
                    Method = filterContext.RequestContext.HttpContext.Request.HttpMethod,
                    filterContext.RequestContext.HttpContext.Request.RawUrl,
                    filterContext.RequestContext.HttpContext.Request.UserAgent
                };
                data = JsonConvert.SerializeObject(request, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

            }
            catch (Exception ex)
            {
                message = ex.Message;
                exceptionType = Common.ExceptionType.LogException;
            }
            finally
            {
                ExceptionLog exceptionLog = new ExceptionLog();
                ExceptionLogBLL exceptionLogBll=new ExceptionLogBLL();

                exceptionLogBll.AddReturnId(new ExceptionLog()
                {
                    CreateDate = DateTime.Now,
                    Url=url,
                    Type = exceptionType.ToString(),
                    ExceptionStack=exception,
                    RequestData = data,
                    Message = message,
                    UserId = userId,
                    Status=BoolType.Fou,  //0:未处理   1:已处理
                    OrderIndex=0,
                    IsDelete = false,
                    ControllerName = controllerName,
                    ActionName = actionName,
                    IsFront = false
                });
            }
        }

        /// <summary>
        /// 在发生异常时调用。
        /// </summary>
        /// <param name="filterContext">操作筛选器上下文。</param>
        public override void OnException(ExceptionContext filterContext)
        {
            //base.OnException(filterContext);
            if (filterContext.Exception.GetType() == typeof(JxException))
            {
                LogException(filterContext, Common.ExceptionType.JxException);
                filterContext.HttpContext.Response.Redirect("~/ShowMsg/Index?msg=" + filterContext.Exception.Message);
                //filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "ShowMsg", action = "Index", msg = filterContext.Exception.Message }));
            }
            else if (filterContext.Exception.GetType() == typeof(JxSuccessMessage))
            {
                filterContext.HttpContext.Response.Redirect("~/ShowMsg/Index?msg=" + filterContext.Exception.Message);
            }
            else if (filterContext.Exception.GetType() == typeof(JxSecurityException))
            {
                LogException(filterContext, Common.ExceptionType.JxSecurityException);
                filterContext.HttpContext.Response.Redirect("~/ShowMsg/Index?msg=" + filterContext.Exception.Message);
            }
            else if (filterContext.Exception.GetType() == typeof(JxMessage))
            {
                filterContext.HttpContext.Response.Redirect("~/ShowMsg/Index?msg=" + filterContext.Exception.Message);
            }
            else if (filterContext.Exception.GetType() == typeof(JxInsideException))
            {
                LogException(filterContext, Common.ExceptionType.JxInsideException);
                filterContext.HttpContext.Response.Redirect("~/ShowMsg/Index?msg=" + filterContext.Exception.Message);
            }
            else
            {
                LogException(filterContext, Common.ExceptionType.UnknownException);
                base.OnException(filterContext);
            }
        }
    }

异常枚举类:

public class ExceptionEnum
    {
        public static Dictionary<string, string> Dictionary = new Dictionary<string, string>()
            {
                {ExceptionType.JxException.ToString(), "异常"},
                {ExceptionType.JxSecurityException.ToString(), "安全性异常"},
                {ExceptionType.JxInsideException.ToString(), "程序代码异常"},
                {ExceptionType.UnknownException.ToString(), "隐性异常"},
                {ExceptionType.LogException.ToString(), "异常记录异常"},
                {ExceptionType.Other.ToString(), "其他"}
            };

    }

    #region Exception

    public enum ExceptionType
    {
        /// <summary>
        /// 异常
        /// </summary>
        [Description("异常")]
        JxException,

        /// <summary>
        /// 安全性异常
        /// </summary>
        [Description("安全性异常")]
        JxSecurityException,

        /// <summary>
        /// 程序代码异常
        /// </summary>
        [Description("程序代码异常")]
        JxInsideException,

        /// <summary>
        /// 隐性异常
        /// </summary>
        [Description("隐性异常")]
        UnknownException,

        /// <summary>
        /// 异常记录异常
        /// </summary>
        [Description("异常记录异常")]
        LogException,

        /// <summary>
        /// 其他
        /// </summary>
        [Description("其他")]
        Other
    }

    #endregion Exception

原文地址:https://www.cnblogs.com/sharing1986687846/p/10362195.html

时间: 2024-10-29 21:01:36

MVC异常捕获处理,FilterConfig的相关文章

.net mvc中AOP 异常捕获后返回自定义的Json

.net mvc中封装了一些特性可以实现AOP,如常用的HandleErrorAttribute,ActionFilterAttribute,AuthorizeAttribute.自定义一个特性,继承这些特性,并重写里面的方法就可以AOP切入到Action中的关注点.本篇文章主要对笔者在使用HandleErrorAttribute的过程中遇到的一个问题进行分享. 我们在action中会用try..catch..进行异常处理,笔者在catch中返回一个json(标示失败).我发现所有的action

MVC 好记星不如烂笔头之 ---&gt; 全局异常捕获以及ACTION捕获

public class BaseController : Controller { /// <summary> /// Called after the action method is invoked. /// </summary> /// <param name="filterContext">Information about the current request and action.</param> protected ov

C#中的那些全局异常捕获

1.WPF全局捕获异常 public partial class App : Application { public App() { // 在异常由应用程序引发但未进行处理时发生.主要指的是UI线程. this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException); //  当某

Spring-MVC开发之全局异常捕获全面解读(转)

异常,异常.我们一定要捕获一切该死的异常,宁可错杀一千也不能放过一个!产品上线后的异常更要命,一定要屏蔽错误内容,以免暴露敏感信息!在用Spring MVC开发WEB应用时捕获全局异常的方法基本有两种: WEB.XML,就是指定error-code和page到指定地址,这也是最传统和常见的做法 用Spring的全局异常捕获功能,这种相对可操作性更强一些,可根据自己的需要做一后善后处理,比如日志记录等. SO,本文列出Spring-MVC做WEB开发时常用全局异常捕获的几种解决方案抛砖引玉,互相没

MVC异常过滤器 (错误页)

控制器 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVC过滤器.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index(string id, string nam

Servlet过滤器——异常捕获过滤器

1.概述 介绍如何实现异常捕获过滤器. 2.技术要点 本实例主要是在过滤器Filter的doFilter()方法中,对执行过滤器链的chain的doFilter()语句处添加try…catch异常捕获语句,然后在chach语句中,循环异常对象,直到找出根异常为止. 3.具体实现 (1)创建Filter实现类ExceptionFilter.java,利用throwable抛出异常,去捕捉异常原因并转到相应的页面中主要代码为: public class ExceptionFilter impleme

Spring-MVC开发之全局异常捕获全面解读

在用Spring MVC开发WEB应用时捕获全局异常的方法基本有两种, WEB.XML,就是指定error-code和page到指定地址,这也是最传统和常见的做法 用Spring的全局异常捕获功能,这种相对可操作性更强一些,可根据自己的需要做一后善后处理,比如日志记录等. SO,本文列出Spring-MVC做WEB开发时常用全局异常捕获的几种解决方案抛砖引玉 互相没有依赖,每个都可单独使用! 定义服务器错误WEB.XML整合Spring MVC web.xml <error-page> <

.NET 基础 一步步 一幕幕[数组、集合、异常捕获]

数组.集合.异常捕获 数组: 一次性存储多个相同类型的变量. 一维数组: 语法: 数组类型[] 数组名=new 数组类型[数组长度]; 声明数组的语法: A.数据类型 [] 数组名称= new 数据类型[2]{1,2}: B.数据类型 [] 数组名称 = new 数据类型[数组大小]; C. 数据类型 [] 数组名称 = {数据,数据,数据,数据}; ***数组的长度一旦固定了,就不能再被改变了 可以通过索引来访问数组中的元素: 数组名称[索引位置] 案例: 多维数组:多个线性数组的值 二维:i

异常捕获

异常捕获,在现在很多ide工具里都可以用快捷键很方便的添加上,防止用户看到自己看不懂的报错甚至莫名其妙崩溃,导致用户体验不好. 哪怕显示一个友好一些的崩溃提示,也比直接显示error:xxxx xxxxxxxxx要好得多. 当然最终的目的还是要给出对应的解决办法,让代码可以继续运行. 1 <?php 2 header("content-type:text/html; charset=utf-8"); 3 /** 4 * 包裹重量异常 5 */ 6 class HeavyParce