关于AOP(面向切面编程)还是先讲一个日常经常碰到的场景“错误日志的记录”,一般来说我们编码的时候想记录错误日志都是用try..catch来进行捕捉和记录,慢慢的你会发现你每一个方法都得加try..catch才能记录每一个方法的错误日志。而有什么办法能做一个统一的拦截呢?做webform的时候可能会用到IHttpModule去实现,也有的会继承HttpApplication去做异常拦截。但这并不能应用在所有的项目场景中,而且这两者针对的对象也不是方法而是http请求。在面对这些场景中AOP就派上用场了。AOP在园子里也不算是一个陌生的话题了,关于AOP理论的文章也是挺多的,也有不少开源的代码,可以很好的帮组我们了解这方面的内容。这段时间自己也是在了解这方面的东西趁着周末的时间就和大家分享一下这方面的内容,代码不高深,写得不好也别吐槽!

 class BaseException : IHttpModule
    {
        #region 接口实现
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.Error += new EventHandler(this.OnError);
        }

        /// <summary>
        /// 释放
        /// </summary>
        public void Dispose()
        {
        }        
        #endregion

        #region 事件
        /// <summary>
        /// 错误事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnError(object sender, EventArgs e)
        {
            this.ExceptionHandle();
        }
        #endregion

        #region 异常处理
        /// <summary>
        /// 异常处理
        /// </summary>
        protected virtual void ExceptionHandle()
        {
            //写异常日志
            Exception finalEx = HttpContext.Current.Server.GetLastError();
            Exception innerEx = finalEx.InnerException;
            while (innerEx != null)
            {
                finalEx = innerEx;
                innerEx = finalEx.InnerException;
            }

            ExceptionLogs.Write(finalEx);//写日志

            //转到异常错误页面
            HttpContext.Current.ApplicationInstance.Server.Transfer("url");
        }
        #endregion

    }
HttpModule拦截日志

相关文章: