zoukankan      html  css  js  c++  java
  • 利用 Application_Error 捕获所有异常 .

    WebApplication开发中通常是需要使用异常捕获,以提供给用户良好的提示页面。

    为了减少代码,统一日志处理,可以在 Global.asax 中 Application_Error 的事件处理方法中统一处理。

    它将捕获所有 Application 级别的 UnhandleException 和 HttpException(比如:访问的页面不存在等)

    总之,在这里处理的话,那么在页面中的所有 try/catch 处理都可以不要了。

        void Application_Error(object sender, EventArgs e) 
        { 
            
    // Code that runs when an unhandled error occurs
            try
            {
                Server.Transfer(
    "~/Error.aspx");
            }
            
    catch
            {
                
    // ignore
            }
        }

    因为 Server.Transfer 将固定抛出 ThreadAbort Exception 异常,不用理会。

    然后在指定的 Error.aspx 里你可以通过  Server.GetLastError() 来进行,错误分类,日志处理,显示信息等工作。

    public partial class Error : System.Web.UI.Page
    {
        
    protected void Page_Load(object sender, EventArgs e)
        {
            
    if (!IsPostBack)
            {
                 Exception ex 
    = Server.GetLastError().GetBaseException();
                 
    this.Label1.Text = DateTime.Now.ToString();
                 
    if (ex != null)
                 {
                      
    // 错误的信息
                      this.Label2.Text = ex.Message;
                      
    // 错误的堆栈
                      this.Label3.Text = ex.StackTrace.Replace("""<br/>"); 
                      
    // 出错的方法名
                      this.Label4.Text = ex.TargetSite.Name;
                      
    // 出错的类名
                      this.Label5.Text = ex.TargetSite.DeclaringType.FullName;
                 }
                 
    // 清空最后的错误
                 Server.ClearError();
            }
        }
    }

    BTW: WinForm开发的时候也可以统一捕获Exception,不过这是在偷懒的时候才会这么干的。

    1. [STAThread]  
    2.        static void Main()  
    3.        {  
    4.            Application.EnableVisualStyles();  
    5.            Application.SetCompatibleTextRenderingDefault(false);  
    6.            Application.Run(new Form1());  
    7.   
    8.            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);  
    9.        }  
    10.   
    11.        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)  
    12.        {  
    13.            // Error Handling   
    14.            MessageBox.Show(e.Exception.Message);  
    15.        }  
  • 相关阅读:
    贪心法(三):POJ题库中的贪心法应用例题
    贪心法(四):HDU题库中的贪心法应用例题
    C语言程序设计100例之(41):快速幂运算
    C语言程序设计100例之(36):四方定理
    C语言程序设计100例之(40):最大公约数问题
    C语言程序设计100例之(38):涂国旗
    相关性搜索简介——常规技术与应用
    Launch X431 HD3卡车诊断适配器评论和反馈
    如何修复更新时卡住的 GODIAG GD801?
    Highend扫描仪比较:Autel vs Snapon vs. Launch vs Bosch
  • 原文地址:https://www.cnblogs.com/Tally/p/2916646.html
Copyright © 2011-2022 走看看