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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Unity | Cinemachine ClearShot Camera[通俗易懂]

    Unity | Cinemachine ClearShot Camera[通俗易懂]ClearShotCamera可以管理一组子虚拟相机,这些虚拟相机需要具有CinemachineCollider组件,ClearShotCamera可以实现角色被障碍物挡住时,虚拟摄像机的自动切换效果,如下所示,角色与Cam2被BoxCollider挡住时,虚拟相机由Cam2自动切换到Cam3。ClearShotCamera上有一个CinemachineClearShot组件,VirtualCameraChildren管理虚拟相机。CinemachineCollider既可以挂在所

    2022年5月28日
    35
  • PHP在线客服系统平台源码(完全开源的网页在线客服系统)

    PHP在线客服系统平台源码(完全开源的网页在线客服系统)  在线客服系统是一个使用PHP、JavaScript和CSS开发的即时网页聊天咨询系统。该项目包含管理员和用户端。管理员端管理所有的管理,如编辑站点内容、管理提供者和预订,管理员在这个系统的管理中起着重要的作用。    在线客服系统源码及演示:zxkfym.top    对于用户部分,用户可以浏览主页、关于和服务。用户可以是顾客谁需要家庭服务或服务提供商提供家庭服务的人。为了注册为服务提供商,用户必须填写注册表格。然而,要将服务提供商作为客户预订,用户可以先搜索可用的服务提供商,然后再进行预订。该

    2022年7月19日
    70
  • CentOS搭建SVN服务器

    CentOS搭建SVN服务器

    2021年6月1日
    100
  • 如何使用eclipse软件创建一个Java项目?[通俗易懂]

    如何使用eclipse软件创建一个Java项目?[通俗易懂]同学们在参加Java的时候老师肯定会教给你们如何去创建一个项目,这里怕有些同学没记住,所以单独为大家分享一篇如何使用eclipse软件创建一个Java项目教程,感觉有用的话收藏转发一下~eclipse创建Java项目教程1.首先我们需要打开eclipse软件,之后找到左上角的file选项卡,点击一下依次选择new-Javaproject选项,如图所示。2.随后会打开一个新建页面,在里面我们找到箭头所示的projectname处,在里面填写我们的Java项目名称,直接选择finish即可完成创建。

    2022年7月9日
    22
  • std::vector初始化[通俗易懂]

    std::vector初始化[通俗易懂]#include<iostream>#include<stdint.h>#include<vector>usingnamespacestd;intmain(){ std::vector<uint8_t>temp0(0,0); cout<<“vectorsize:”<<temp0.size()<<endl; std::vector<uint8_t>temp1(.

    2022年9月16日
    2
  • pycharm调试远程主机_服务终端

    pycharm调试远程主机_服务终端我们有时为了方便,可能需要用到pycharm中的终端功能进行服务器端调试。在将pycharm配置远程开发后,我们点开Terminal终端功能,默认是本地的终端,如下图。如果要使用远程的终端,非常简单,因为已经配置过远程的解释器,我们点开Tools里的startSSHsession功能,即可选择服务器端的终端功能按图示选择完后,就可以直接使用服务器端的终端功能了,不需要额外的SSH工具显…

    2022年8月28日
    4

发表回复

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

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