asp net mvc 全局捕获异常的方法

asp net mvc 全局捕获异常的方法在一个网站的开发测试阶段,我们经常需要全局捕获异常。使得网站在异常发生时并不会整个崩掉,从而影响到所有用户的访问,同时记录下异常的详细信息,以便于网站维护人员在异常发生后,可以准确定位异常所在位置和原因。本文使用过滤器的方式来实现全局异常捕获。网上也有很多类似的博文教程,我这里整理了一份日志打印比较完整的。新建过滤器在您的Util项目添加过滤器ExceptionLogAttribute.cs:usingSystem;usingSystem.Web;usingSystem.Web.Mv

大家好,又见面了,我是你们的朋友全栈君。

在一个网站的开发测试阶段,我们经常需要全局捕获异常。使得网站在异常发生时并不会整个崩掉,从而影响到所有用户的访问,同时记录下异常的详细信息,以便于网站维护人员在异常发生后,可以准确定位异常所在位置和原因。本文使用过滤器的方式来实现全局异常捕获。网上也有很多类似的博文教程,我这里整理了一份日志打印比较完整的。

新建过滤器

在您的Util项目添加过滤器ExceptionLogAttribute.cs:

using System;
using System.Web;
using System.Web.Mvc;
using YourNameSpace.Util.Helpper;
using NLog;

namespace YourNameSpace.Util.Extensions
{
    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class ExceptionLogAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                try
                {
                    var controllerName = (string)filterContext.RouteData.Values["controller"];
                    var actionName = (string)filterContext.RouteData.Values["action"];
                    var memberId = filterContext.Controller.ViewBag.MemberId;
                    var exception = filterContext.Exception;
                    if (filterContext.HttpContext != null && filterContext.HttpContext.Request != null)
                    {
                        if (filterContext.HttpContext.Request.RequestType == "GET")
                        {
                            var requestUrl = filterContext.HttpContext.Request.Url.ToString();
                            var requestParas = filterContext.HttpContext.Request.Params;
                            if (requestParas != null)
                            {
                                var reqParaStr = HttpUtility.UrlDecode(requestParas.ToString());
                                logger.Error(LoggerHelper.GetErrorMsg(exception, controllerName, actionName, memberId, requestUrl, reqParaStr));
                            }
                            else
                            {
                                logger.Error(LoggerHelper.GetErrorMsg(exception, controllerName, actionName, memberId, requestUrl));
                            }
                        }
                        else if (filterContext.HttpContext.Request.RequestType == "POST")
                        {
                            var requestUrl = filterContext.HttpContext.Request.Url.ToString();
                            var requestParas = filterContext.HttpContext.Request.Params;
                            if (requestParas != null)
                            {
                                var reqParaStr = HttpUtility.UrlDecode(requestParas.ToString());
                                logger.Error(LoggerHelper.GetErrorMsg(exception, controllerName, actionName, memberId, requestUrl, reqParaStr));
                            }
                            else
                            {
                                logger.Error(LoggerHelper.GetErrorMsg(exception, controllerName, actionName, memberId, requestUrl));
                            }
                        }
                        else
                        {
                            logger.Error(LoggerHelper.GetErrorMsg(exception, controllerName, actionName, memberId));
                        }
                    }
                    else
                    {
                        logger.Error(LoggerHelper.GetErrorMsg(exception, controllerName, actionName, memberId));
                    }
                }
                catch (Exception e)
                {
                    logger.Error(LoggerHelper.GetErrorMsg(e, "ExceptionLogAttribute", "异常过滤器", "未知"));
                }
            }
            filterContext.ExceptionHandled = true;
        }
    }
}

关于NLog的配置和使用,本文不再赘述。可自行百度进行配置。

在您的Util项目中添加日志帮助类LoggerHelper.cs:

using System;using System.Text;namespace YourNameSpace.Util.Helpper{    public class LoggerHelper    {        public static string GetErrorMsg(Exception exception, string controllerName, string actionName, Guid memberId, string requestUrl = null, string requestParams = null, string extraMsg = null)        {            return GetErrorMsg(exception, controllerName, actionName, memberId.ToString(), requestUrl, requestParams, extraMsg);        }        /// <summary>        /// 获取接口异常详细信息函数        /// </summary>        /// <param name="exception">异常对象</param>        /// <param name="controllerName">控制器名称</param>        /// <param name="actionName">接口名称</param>        /// <param name="memberId">用户Id</param>        /// <param name="requestUrl">请求URL</param>        /// <param name="requestParams">请求参数</param>        /// <param name="extraMsg">需要额外打印输出的日志信息</param>        /// <returns></returns>        public static string GetErrorMsg(Exception exception, string controllerName, string actionName, string memberId, string requestUrl = null, string requestParams = null, string extraMsg = null)        {            var erroMsg = new StringBuilder();            if (!string.IsNullOrWhiteSpace(extraMsg))            {                erroMsg.Append(extraMsg);            }            erroMsg.Append($"控制器:{controllerName}/{actionName} \n") ;            if(string.IsNullOrWhiteSpace(memberId))            {                erroMsg.Append($"无用户Id \n ");            }            else            {                erroMsg.Append($"用户Id:{memberId} \n ");            }            erroMsg.Append($"ExceptionMessage:{exception.Message} \n InnerException:{exception.InnerException} \n StackTrace:{exception.StackTrace} \n");            if (!string.IsNullOrWhiteSpace(requestUrl))            {                erroMsg.Append($"Request.Url:{requestUrl} \n");            }            if (!string.IsNullOrWhiteSpace(requestParams))            {                erroMsg.Append($"Request.Params:{requestParams} \n");            }            return erroMsg.ToString();        }    }}

注册全局过滤器

在【您的web项目】->【App_Start】->【FilterConfig.cs】中引用过滤器,并注册全局异常捕获过滤器。

asp net mvc 全局捕获异常的方法

 

using System.Web.Mvc;using YourNameSpace.Util.Filters;using YourNameSpace.Util.Extensions;namespace YourNameSpace.Web{    public class FilterConfig    {        public static void RegisterGlobalFilters(GlobalFilterCollection filters)        {            //注册全局过滤器            filters.Add(new HandleErrorAttribute());            //注册全局异常捕获过滤器            filters.Add(new ExceptionLogAttribute());        }    }}

 

全局异常日志打印结果

asp net mvc 全局捕获异常的方法

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/162923.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • ups不间断电源介绍_ups不间断电源设备有哪几部分组成

    ups不间断电源介绍_ups不间断电源设备有哪几部分组成本文简单介绍UPS(不间断电源)的相关知识。1概述UPS(UninterruptedPowerSupply),即不间断电源,是将蓄电池与主机相连接,通过主机逆变器等模块电路,将蓄电池中直流(DC,DirectCurrent)电转换成市电交流(AC,AlternatingCurrent)电的系统设备。UPS主要用于给单台计算机、计算机网络系统或其它电力电子设备如电磁阀、压力变送器…

    2025年7月12日
    3
  • DVP,LVDS和MIPI「建议收藏」

    DVP,LVDS和MIPI「建议收藏」Mipi接口和LVDS接口区别主要区别:1.LVDS接口只用于传输视频数据,MIPIDSI不仅能够传输视频数据,还能传输控制指令;2.LVDS接口主要是将RGBTTL信号按照SPWG/JEIDA格式转换成LVDS信号进行传输,MIPIDSI接口则按照特定的握手顺序和指令规则传输屏幕控制所需的视频数据和控制数据。液晶屏有RGBTTL、LVDS、MIPIDSI接口…

    2022年5月4日
    170
  • eXtremeComponents总结(转载)[通俗易懂]

    eXtremeComponents总结(转载)[通俗易懂]文章来源:http://www.blogjava.net/amigoxie/archive/2008/01/08/173526.html  作者:阿蜜果 1.简介eXtremeComponents(简称ec)是一系列提供高级显示的开源JSP定制标签,当前的包含的组件为eXtremeTable,用于以表形式显示数据。使用ec需要一定的前提条件,JDK要求1.3或更高的版本,Servlet需要…

    2022年8月20日
    6
  • android四种启动模式_Android Terminal Emulator

    android四种启动模式_Android Terminal Emulator本文转载自:http://blog.csdn.net/MyArrow/article/details/8136018(1)添加头文件:#include<linux/earlysuspend.h>(2)在特定驱动结构体中添加early_suspend结构:#ifdefCONFIG_HAS_EARLYSUSPENDstructearly_suspendea…

    2022年9月18日
    2
  • mybatis自定义排序_oracle排序分页查询

    mybatis自定义排序_oracle排序分页查询importtk.mybatis.mapper.entity.Example;importcom.github.pagehelper.PageHelper;…@OverridepublicList<Repayxxx>listRepaymentPlan(Integerstart){Exampleex…

    2022年9月22日
    3
  • 程序员写代码都用什么样的笔记本?

    程序员写代码都用什么样的笔记本?程序员一般喜欢用thinkpad或者Mac,因为价位等方面的因素,还是用thinkpad多点,从事不同研发方向需要的计算机的配置也不太相同,现在开发软件要求的机器配置也和十几年不太一样,那个时候嵌入式刚好是红利期,很多的培训机构呼呼涉足这个领域,那个时期AMD的cpu还能和intel抗衡一下,不像现在有这么大的差异,记得第一家公司属于创业性质的公司,公司配置的电脑是神州牌子的,在上面开发软件,需要…

    2022年5月29日
    52

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号