• asp.net 利用Global.asax 捕获整个解决方案中的异常错误


    之前做项目的时候都是在每个页面中处理这不同的异常信息,一个页面数下来,很多个try{}catch{}语句块,令整个代码结构有些不够美观。

                今天看到一篇帖子,是关于利用全局应用程序类来帮忙获取异常信息,利用 server.Transfer('''')指定接受错误的页面;加上在接受错误页面中利用 server.GetLastError() 获取前一个异常源。

                Global.asax 中的Application_Error 函数如下:

               

    1. protected void Application_Error(object sender, EventArgs e)  
    2.        {  
    3.            //捕获整个解决方案下的所有异常   
    4.            try  
    5.            {  
    6.                Server.Transfer("~/Error.aspx");  
    7.            }  
    8.            catch { }  
    9.        }  

                错误接受页面 Error.aspx 获取异常信息的相关代码如下:

               

    1. Exception ex = Server.GetLastError().GetBaseException(); //获取异常源   
    2.                if (ex != null)  
    3.                {    
    4.                    Response.Write(ex.Message);      
    5.                }  
    6.                //清空前一个异常   
    7.                Server.ClearError();  

                测试页面Text.aspx中的测试异常代码如下:

               

    1. //测试是否捕获了异常信息   
    2.    //test1   
    3.   //int UserID = Convert.ToInt32(Request["UserID"].ToString());   
    4.   
    5.   
    6.   //test2   
    7.   string Name = "aganar";  
    8.   
    9.   int UID = Convert.ToInt32(Name);  

                运行Test.aspx页面,我们会看到相关的异常信息,我们能够清晰地看出,在页面Test.aspx页面中未曾有任何一个try{}catch{}语句块存在,我们即可很方便轻松地捕获到异常信息

  • 相关阅读:
    centos 安装docker-ce
    quartz.net .netcore 定时任务部署到linux
    c# 获取linux 磁盘信息
    nginx 安装
    async await 理解
    Remote side unexpectedly closed network connection
    centos 安装。net
    yum 操作
    centos7下安装mysql5.7
    git 本地仓库版本无法从远程更新到本地
  • 原文地址:https://www.cnblogs.com/fanjiming/p/2246959.html
Copyright © 2020-2023  润新知