﻿// ***********************************************************************
// Assembly         : Bocai.Common
// Author           : Bocai
// Created          : 2013-10-22
//
// <copyright file="ExceptionHttpModule.cs" company="Bocai.Inc">
//     Copyright (c) Bocai.Inc. All rights reserved.
// </copyright>
// ***********************************************************************
using System;
using System.Web;
using Bocai.Common.Loger.LogDTO;
using Bocai.Common.Utilities;

/// <summary>
/// The HttpModule namespace.
/// </summary>
namespace Bocai.Common.HttpModule
{
    /// <summary>
    /// 异常处理模块
    /// </summary>
    /// <remarks>
    ///  Last Modified By : Bocai<br />
    ///  Last Modified On : 2013-12-20 23:28:49
    /// </remarks>
    public class ExceptionHttpModule : IHttpModule
    {
        /// <summary>
        /// 初始化监测程序
        /// </summary>
        /// <param name="application">The application.</param>
        public void Init(HttpApplication application)
        {
            application.Error += new EventHandler(application_Error);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }
        /// <summary>
        /// 在出现未处理的错误时运行的代码IHttpModule
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        void application_Error(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            Exception ex = context.Server.GetLastError().GetBaseException();

            ExceptionDTO dto = ExceptionHelper.FillExceptionDto(context, ex);

            LogHelper.Error(dto);
        }
        /// <summary>
        /// 当某个异常未被捕获时出现
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            ExceptionDTO dto = ExceptionHelper.FillExceptionDto(HttpContext.Current, ex);

            LogHelper.Error(dto);
        }

        #region IHttpModule 成员

        /// <summary>
        /// 处置由实现 <see cref="T:System.Web.IHttpModule" /> 的模块使用的资源（内存除外）。
        /// </summary>
        public void Dispose()
        {

        }

        #endregion
    }
}
