Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 645|回复: 0

asp.net mvc ,asp.net mvc api 中使用全局过滤器进行异常捕获记录

[复制链接]
  • TA的每日心情
    奋斗
    2024-11-24 15:47
  • 签到天数: 804 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    726782
    发表于 2021-7-22 10:30:49 | 显示全部楼层 |阅读模式

    MVC下的全局异常过滤器注册方式如下:标红为asp.net mvc ,asp.net mvc api  注册全局异常过滤器的不同之处

    using SuperManCore;
    using System.Web;
    using System.Web.Mvc;
    
    namespace SuperMan
    {
        public class FilterConfig
        {
            /// <summary>
            /// 注册全局过滤器 add by caoheyang 20150205
            /// </summary>
            /// <param name="filters"></param>
            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new WebHandleErrorAttribute(), 1);
                filters.Add(new HandleErrorAttribute(), 2);
            }
        }
    
    
        /// <summary>
        /// 自定义异常处理类  add by caoheyang 20150205
        /// </summary>
        public class WebHandleErrorAttribute : HandleErrorAttribute
        {
            /// <summary>
            /// 重写异常处理方法 add by caoheyang 20150205   需要将该特性标注于各个controller上。
            /// </summary>
            /// <param name="filterContext">上下文对象  该类继承于ControllerContext</param>
            public override void OnException(ExceptionContext filterContext)
            {
                LogHelper.LogWriterFromFilter(filterContext.Exception);
            }
        }
    }
    MVC API下的注册方式如下:
    在WebApiConfig.cs文件下加入标红代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Web.Http;
    using Microsoft.Owin.Security.OAuth;
    using Newtonsoft.Json.Serialization;
    
    namespace SuperManWebApi
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API 配置和服务
                // 将 Web API 配置为仅使用不记名令牌身份验证。
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
          config.Filters.Add(new ApiHandleErrorAttribute());  //注册全局异常过滤器 add by caoheyang 20150206     不需要将该特性标注于各个controller上
                // Web API 路由
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",                
                    routeTemplate: "{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }
     /// <summary>
        /// 自定义异常处理类  add by caoheyang 20150205   不需要将该特性标注于各个controller上。 /// </summary>
        public class ApiHandleErrorAttribute : ExceptionFilterAttribute
        {
            /// <summary>
            /// 重写异常处理方法 add by caoheyang 20150205
            /// </summary>
            /// <param name="filterContext">上下文对象</param>
            public override void OnException(HttpActionExecutedContext filterContext)
            {
                LogHelper.LogWriterFromFilter(filterContext.Exception);
            }
    }


    另外附LogHelper源码:
    public class LogHelper
        {
           public static Logger logger = LogManager.GetLogger("SuperManCore.LogHelper");
      
           /// <summary>
           /// 备注日志
           /// </summary>
           /// <param name="dec">需要捕获的参数(必须为属性类)</param>
           /// <param name="rmark">描述操作</param>
           public new static void LogWriter(string rmark="",object dec=null)
           {
               try
               {
                   string logstr = "\r\n-----------------start----------------------\r\n";
                   MethodBase m = new StackTrace().GetFrame(1).GetMethod();
                   ParameterInfo[] pm = m.GetParameters();
                   string classname = m.DeclaringType.ToString();
                   string propertyName = m.Name;
                   logstr = logstr + "备注:" + rmark + "\r\n";
                   //写类名
                   logstr = logstr + "函数类名:" + classname + "\r\n";
                   //写函数方法
                   logstr = logstr + "函数名称为:" + propertyName + "\r\n";
                   for (int i = 0; i < pm.Length; i++)
                   {
                       logstr = logstr + "函数的参数有:" + pm.Name.ToString() + "\r\n";
                   }
                   JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                   logstr = logstr + "函数参数值:" + jsonSerializer.Serialize(dec) + "\r\n";
                   logstr += "--------------------end---------------------\r\n";
                   //写日志
                   logger.Info(logstr);
               }
               catch (Exception)
               {
    
                   throw;
               }
    
           }  
    
           /// <summary>
           /// 异常捕获日志
           /// </summary>
           /// <param name="ex">异常对象(必须为属性类)</param>
           /// <param name="rmark">操作简要描述</param>
           public new static void LogWriter(Exception ex, string rmark="")
           {
               try
               {
                   string logstr = "\r\n-----------------start----------------------\r\n";
                   MethodBase m = new StackTrace().GetFrame(1).GetMethod();
                   ParameterInfo[] pm = m.GetParameters();
                   string classname = m.DeclaringType.ToString();
                   string propertyName = m.Name;
                   logstr = logstr + "备注:" + rmark + "\r\n";
                   //写类名
                   logstr = logstr + "函数类名:" + classname + "\r\n";
                   //写函数方法
                   logstr = logstr + "函数名称为:" + propertyName + "\r\n";
                   for (int i = 0; i < pm.Length; i++)
                   {
                       logstr = logstr + "函数的参数有:" + pm.Name.ToString() + "\r\n";
                   }
                   logstr = logstr + "函数异常:" + ex.ToString() + "\r\n";
                   logstr += "--------------------end---------------------\r\n";
                   //写日志
                   logger.Info(logstr);
               }
               catch (Exception)
               {
                   throw;
               }
    
           }
           /// <summary>
           /// 带参数 异常的日志
           /// </summary>
           /// <param name="dec">异常参数对象(必须为属性类)</param>
           /// <param name="ex">日志异常对象</param>
           public new static void LogWriter(object dec, Exception ex)
           {
               try
               {
                   string logstr = "\r\n-----------------start----------------------\r\n";
                   MethodBase m = new StackTrace().GetFrame(1).GetMethod();
                   ParameterInfo[] pm = m.GetParameters();
                   string classname = m.DeclaringType.ToString();
                   string propertyName = m.Name;
                   //写类名
                   logstr = logstr + "函数类名:" + classname + "\r\n";
                   //写函数方法
                   logstr = logstr + "函数名称为:" + propertyName + "\r\n";
                   for (int i = 0; i < pm.Length; i++)
                   {
                       logstr = logstr + "函数的参数有:" + pm.Name.ToString() + "\r\n";
                   }
                   JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                   logstr = logstr + "函数参数值:" + jsonSerializer.Serialize(dec) + "\r\n";
                   logstr = logstr + "函数异常:" + ex.ToString() + "\r\n";
                   logstr += "--------------------end---------------------\r\n";
                   //写日志
                   logger.Info(logstr);
               }
               catch (Exception)
               {
                   throw;
               }
    
           }
           /// <summary>
           /// 带参数 描述 异常日志捕获
           /// </summary>
           /// <param name="dec">所要捕获的参数(必须为属性类)</param>
           /// <param name="ex">异常对象</param>
           /// <param name="rmark">描述</param>
           public new static void LogWriter(object dec, Exception ex, string rmark)
           {
               try
               {
                   string logstr = "\r\n-----------------start----------------------\r\n";
                   MethodBase m = new StackTrace().GetFrame(1).GetMethod();
                   ParameterInfo[] pm = m.GetParameters();
                   string classname = m.DeclaringType.ToString();
                   string propertyName = m.Name;
                   //写备注
                   logstr = logstr + "备注:" + rmark + "\r\n";
                   //写类名
                   logstr = logstr + "函数类名:" + classname + "\r\n";
                   //写函数方法
                   logstr = logstr + "函数名称为:" + propertyName + "\r\n";
                   for (int i = 0; i < pm.Length; i++)
                   {
                       logstr = logstr + "函数的参数有:" + pm.Name.ToString() + "\r\n";
                   }
                   JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                   logstr = logstr + "函数参数值:" + jsonSerializer.Serialize(dec) + "\r\n";
                   logstr = logstr + "函数异常:" + ex.ToString() + "\r\n";
                   logstr += "--------------------end---------------------\r\n";
                   //写日志
                   logger.Info(logstr);
               }
               catch (Exception)
               {
                   throw;
               }
           }
           /// <summary>
           /// 捕获全局异常
           /// </summary>
           /// <param name="error"></param>
           public new static void LogWriterFromFilter(Exception error)
           {
               try
               {
                   string logstr = "\r\n-----------------start----------------------\r\n"; 
                   //异常发生地址
                   logstr = logstr + "异常发生地址:" + HttpContext.Current.Request.Url.AbsoluteUri.ToString() + "\r\n";
                   logstr = logstr + "请求类型:" + HttpContext.Current.Request.RequestType.ToString() + "\r\n";
                   
                   logstr = logstr + "异常:" + error.ToString() + "\r\n";
                    
                   logstr += "--------------------end---------------------\r\n";
                   //发送邮件
                   if (ConfigSettings.Instance.IsSendMail == "true")
                   {
                       string emailToAddress = ConfigSettings.Instance.EmailToAdress;
                       EmailHelper.SendEmailTo(logstr, emailToAddress);
                   }              
                   //写日志
                   logger.Info(logstr);
               }
               catch (Exception)
               {
                   throw;
               } 
           }
        }

    注:LogHelper所在类库需要引用NLog.dll文件。

     
    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-12-22 11:01 , Processed in 0.058661 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表