ASP.NET MVC全局異常捕獲過濾器

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Transaction.FrameWork;
using Transaction.FrameWork.log4net;

namespace Transaction.Site
{
    /// 
    /// 全局异常处理过滤器
    /// 
    public class ExceptionFilter : IExceptionFilter
    {
        /// 
        /// 全局异常处理
        /// 
        /// 
        public void OnException(ExceptionContext filterContext)
        {
            ApiResult backMsg = new ApiResult();
            //是否记录日志
            bool isLog = false;
            if (filterContext.Exception != null)
            {
                if (filterContext.Exception is ArgumentException)
                {
                    RedirectResult result = new RedirectResult("/home/index");
                    filterContext.Result = result;
                    filterContext.ExceptionHandled = true;
                    return;
                }
                backMsg.success = false;
                backMsg.msg = filterContext.Exception.Message;
                if (filterContext.Exception.InnerException != null)
                {
                    backMsg.msg = filterContext.Exception.InnerException.Message;
                }
                if (filterContext.Exception is FrameWork.Exceptions.TipException) //手动抛出消息异常
                {
                    isLog = false;
                }
                else if (filterContext.Exception is DbException) //数据库执行异常
                {
                    //DbException exception = filterContext.Exception as DbException;
                    isLog = true;
                }
                else
                {
                    isLog = true;    //执行程序异常            
                }
            }
            if (isLog)
            {
                //记录错误日志
                if (filterContext.Exception.InnerException != null)
                {
                    LogHelper.LogError(backMsg.msg, filterContext.Exception.InnerException);
                }
                else
                {
                    LogHelper.LogError(backMsg.msg, filterContext.Exception);
                }
            }
            bool isAjax = filterContext.HttpContext.Request.IsAjaxRequest();
            if (isAjax)
            {
                //ajax请求
                JsonResult jsonResult = new JsonResult() { Data = backMsg };
                filterContext.Result = jsonResult;
                filterContext.ExceptionHandled = true;
            }          
            //讀取webconfig的值,看是否是開發環境,開發環境如果運行異常會自動顯示異常消息在頁面,發佈環境不會顯示異常消息
            System.Web.Configuration.CompilationSection cmp = (System.Web.Configuration.CompilationSection)System.Configuration.ConfigurationManager.GetSection("system.web/compilation");
            if (cmp != null)
            {
                if (!cmp.Debug)
                {
                    filterContext.ExceptionHandled = true;
                }
            }
        }
    }
}

在Global.asax裡面設置註冊全局過濾器

protected void Application_Start()
{
    GlobalFilters.Filters.Add(new ExceptionFilter());
}

这里是另一个OnException异常方法的实现参考:

 /// 
        /// 自定义异常处理
        /// 
        /// 
        protected override void OnException(ExceptionContext exceptionContext)
        {
            //记录本地文件日志
            Task.Run(() => LogHelper.AddLog(exceptionContext.Exception.ToString()));
            var result = new Result
            {
                Status = false,
                Message = exceptionContext.Exception.Message,
                StatusCode = "0"
            };
            if (exceptionContext.HttpContext.Request.IsAjaxRequest())
            {
                exceptionContext.Result = Json(result, JsonRequestBehavior.AllowGet);
            }
#if !DEBUG
            else
            {  
                ViewResult viewResult = new ViewResult();
                //这里的Error视图是在Shared文件夹里面,他没有Action
                viewResult.ViewName = "Error";          
                exceptionContext.Result = viewResult;               
                exceptionContext.HttpContext.Response.Clear();
            }
            exceptionContext.ExceptionHandled = true;
#endif 
        }

你可能感兴趣的:(ASP.NET,MVC)