在MVC項目中使用異常處理

1.首先在【Model】中新建一個class作異常處理。該類繼承自:HandleErrorAttribute,須要導入命名空間。html

 

 

public class MyExceptionAttribute:HandleErrorAttribute
    {


        //新建一個異常隊列(同一個隊列)
        //public Queue<Exception> ExceptionQueue = new Queue<Exception>();
        //改成靜態的,否則每次都會建立一個隊列,不會在同一個隊列中添加數據
        public static Queue<Exception> ExceptionQueue = new Queue<Exception>();


        /// <summary>
        /// 能夠捕獲異常數據,實現父類的OnException方法
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            Exception ex = filterContext.Exception;
            //將數據寫到隊列,入隊
            ExceptionQueue.Enqueue(ex);
            //跳轉到錯誤頁面
            filterContext.HttpContext.Response.Redirect("/Error.html");
        }
    }

 

2.在FilterConfig.cs文件中註冊本身定義的過濾器。ide

相關文章
相關標籤/搜索