zoukankan      html  css  js  c++  java
  • MVC 全局异常捕获

    /// <summary>
        /// 自定义全局异常捕获
        /// </summary>
        public class ExceptionHelper : FilterAttribute, IExceptionFilter
        {
            /// <summary>
            /// 实现 IExceptionFilter中的 OnException 方法
            /// </summary>
            /// <param name="filterContext"></param>
            public void OnException(ExceptionContext filterContext)
            {
                Exception ex = filterContext.Exception as Exception;
                if (ex != null)
                {
                    filterContext.Controller.ViewBag.UrlRefer = filterContext.HttpContext.Request.UrlReferrer;
                    LogHelper.Error("Filter捕获到未处理异常",ex);            
                    //页面抛出异常信息
                    filterContext.HttpContext.Response.Write(string.Format("系统捕捉到未处理的异常:{0}<br/>", ex.GetType().ToString()));
                    filterContext.HttpContext.Response.Write("Filter 已进行错误处理。");
                }
                filterContext.ExceptionHandled = true;//设置异常已经处理
            }
        }

    自定义一个类,继承 FilterAttribute,IExceptionFilter。实现接口OnException,该接口为程序抛异常时触发。

    在MVC的Filter.config中添加该类。

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new HandleErrorAttribute());
                filters.Add(new ExceptionHelper(), 1);//自定义的验证特性 ExceptionHelper
         }

    这样在MVC中就可以捕获没有处理的异常信息。

  • 相关阅读:
    LeetCode OJ
    LeetCode OJ
    LeetCode OJ
    网页排版中的浮动和定位(学习笔记)
    在html中,<input tyle = "text">除了text外还有几种种新增的表单元素
    初学者入门web前端:C#基础知识:函数
    初学者入门web前端 C#基础知识:数组与集合
    while/for循环
    jmeter http请求与参数化
    rpm -e --nodeps
  • 原文地址:https://www.cnblogs.com/daniel-niu/p/10313206.html
Copyright © 2011-2022 走看看