Catching unhandled exceptions in ASP.NET UserControls

前端 未结 7 1984
猫巷女王i
猫巷女王i 2021-01-06 00:58

I\'m dynamically loading user controls adding them to the Controls collection of the web form.

I\'d like to hide user controls if they cause a unhandled exception wh

7条回答
  •  难免孤独
    2021-01-06 01:24

    I used @Keith's approach, but the problem is that the control is rendered up until the Exception is thrown, potentially resulting in open HTML tags. I'm also rendering the exception information in the Control if in Debug mode.

      protected override void Render(System.Web.UI.HtmlTextWriter writer)
      {
         try
         {
            // Render the module to a local a temporary writer so that if an Exception occurs
            // the control is not halfway rendered - "it is all or nothing" proposition
            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
            base.Render(htw);
    
            // We made it!  Copy the Control Render over
            writer.Write(sw.GetStringBuilder().ToString());
         }
         catch (System.Exception ex)
         {
            string message = string.Format("Error Rendering Control {0}\n", ID);
            Log.Error(message, ex);
            if (Page.IsDebug)
               writer.Write(string.Format("{0}
    Exception:
    {1}\n{2}
    ", message, ex.Message, ex.StackTrace)); } }

提交回复
热议问题