<p>I'm dynamically loading user controls adding them to the Controls collection of the web form.</p>

<p>I'd like to hide user controls if they cause a unhandled exception while rendering.</p>

<p>So, I tried hooking to the Error event of each UserControl but it seems that this event never fires for the UserControls as it does for Page class. </p>

<p>Did some googling around and it doesn't seem promising. Any ideas here?</p>

[{'answer_id': 10797, 'author': 'Michael Stum', 'author_id': 91, 'author_profile': 'https://Stackoverflow.com/users/91', 'pm_score': 0, 'selected': False, 'text': '<p>Global.asax and Application_Error?</p>\n\n<p><a href="http://www.15seconds.com/issue/030102.htm" rel="nofollow noreferrer">http://www.15seconds.com/issue/030102.htm</a></p>\n\n<p>Or the Page_Error Event on an individual Page only:</p>\n\n<p><a href="http://support.microsoft.com/kb/306355" rel="nofollow noreferrer">http://support.microsoft.com/kb/306355</a></p>\n\n<pre><code>void Page_Load(object sender, System.EventArgs e)\n{\n    throw(new ArgumentNullException());\n}\n\npublic void Page_Error(object sender,EventArgs e)\n{\n    Exception objErr = Server.GetLastError().GetBaseException();\n    string err =    "&lt;b&gt;Error Caught in Page_Error event&lt;/b&gt;&lt;hr&gt;&lt;br&gt;" + \n                    "&lt;br&gt;&lt;b&gt;Error in: &lt;/b&gt;" + Request.Url.ToString() +\n                    "&lt;br&gt;&lt;b&gt;Error Message: &lt;/b&gt;" + objErr.Message.ToString()+\n                    "&lt;br&gt;&lt;b&gt;Stack Trace:&lt;/b&gt;&lt;br&gt;" + \n                      objErr.StackTrace.ToString();\n    Response.Write(err.ToString());\n    Server.ClearError();\n}\n</code></pre>\n\n<p>Also, Karl Seguin (Hi Karl!) had a Post on using HttpHandler instead:</p>\n\n<p><a href="http://codebetter.com/blogs/karlseguin/archive/2006/06/12/146356.aspx" rel="nofollow noreferrer">http://codebetter.com/blogs/karlseguin/archive/2006/06/12/146356.aspx</a></p>\n\n<p>(Not sure what the permission to reproduce it, but if you want to write up an answer, you got my Upvote ☺)</p>\n'}, {'answer_id': 10812, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 0, 'selected': False, 'text': '<p>How about adding a new sub-class of UserControl that error-handles its render and load methods (so that they hide as you wish) and then inheriting from that for your user controls?</p>\n'}, {'answer_id': 10815, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 2, 'selected': False, 'text': '<p>This is an interesting problem.. I am still pretty fresh when it comes to custom controls etc, but here are my thoughts (feel free to comment/correct people!).. (I am kinda thinking/writing out loud here!)</p>\n\n<ul>\n<li>If an error occurs during rendering, in some cases, would it not be too late? (since some of the controls HTML may have already been sent to the Writer and output).</li>\n<li>Therefore, would it not be best to wrap the user control\'s Render method, but rather than passing it the reference to the "Live" HtmlTextWriter, you pass your own, trap any Exceptions raised in this little safety "bubble", if all goes well, you then pass your resultant HTML to the actual HtmlTextWriter?</li>\n<li>This logic could probably be slung to a generic wrapper class which you would use to dynamically load/render the controls at run time..</li>\n<li>If any errors do occur, you have all the information you need at your disposal! (i.e control references etc).</li>\n</ul>\n\n<p>Just my thoughts, flame away! :D ;)</p>\n'}, {'answer_id': 10916, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 1, 'selected': False, 'text': "<p>Depending on where your errors are occurring you can do something like...</p>\n\n<pre><code>public abstract class SilentErrorControl : UserControl\n{\n    protected override void Render( HtmlTextWriter writer )\n    {\n        //call the base's render method, but with a try catch\n        try { base.Render( writer ); }\n        catch ( Exception ex ) { /*do nothing*/ }\n    }\n}\n</code></pre>\n\n<p>Then inherit SilentErrorControl instead of UserControl.</p>\n"}, {'answer_id': 12055, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 5, 'selected': True, 'text': '<p>mmilic, following on from <a href="https://stackoverflow.com/questions/10793/catching-unhandled-exceptions-in-aspnet-usercontrols#10910">your response</a> to my <a href="https://stackoverflow.com/questions/10793/catching-unhandled-exceptions-in-aspnet-usercontrols#10815">previous idea</a>..</p>\n\n<p>No additional logic required! That\'s the point, your doing nothing to the classes in question, just wrapping them in some instantiation bubble-wrap! :)</p>\n\n<p>OK, I was going to just bullet point but I wanted to see this work for myself, so I cobbled together some <em>very</em> rough code but the concept is there and it seems to work.</p>\n\n<p><strong>APOLOGIES FOR THE LONG POST</strong></p>\n\n<h2>The SafeLoader</h2>\n\n<p>This will basically be the "bubble" I mentioned.. It will get the controls HTML, catching any errors that occur during Rendering.</p>\n\n<pre><code>public class SafeLoader\n{\n    public static string LoadControl(Control ctl)\n    {\n        // In terms of what we could do here, its down\n        // to you, I will just return some basic HTML saying\n        // I screwed up.\n        try\n        {\n            // Get the Controls HTML (which may throw)\n            // And store it in our own writer away from the\n            // actual Live page.\n            StringWriter writer = new StringWriter();\n            HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);\n            ctl.RenderControl(htmlWriter);\n\n            return writer.GetStringBuilder().ToString();\n        }\n        catch (Exception)\n        {\n            string ctlType = ctl.GetType().Name;\n            return "&lt;span style=\\"color: red; font-weight:bold; font-size: smaller;\\"&gt;" + \n                "Rob + Controls = FAIL (" + \n                ctlType + " rendering failed) Sad face :(&lt;/span&gt;";\n        }\n    }\n}\n</code></pre>\n\n<h2>And Some Controls..</h2>\n\n<p>Ok I just mocked together two controls here, one will throw the other will render junk. Point here, I don\'t give a crap. These will be replaced with your custom controls..</p>\n\n<h3>BadControl</h3>\n\n<pre><code>public class BadControl : WebControl\n{\n    protected override void Render(HtmlTextWriter writer)\n    {\n        throw new ApplicationException("Rob can\'t program controls");\n    }\n}\n</code></pre>\n\n<h3>GoodControl</h3>\n\n<pre><code>public class GoodControl : WebControl\n{\n    protected override void Render(HtmlTextWriter writer)\n    {\n        writer.Write("&lt;b&gt;Holy crap this control works&lt;/b&gt;");\n    }\n}\n</code></pre>\n\n<h2>The Page</h2>\n\n<p>OK, so lets look at the "test" page.. Here I simply instantiate the controls, grab their html and output it, I will follow with thoughts on designer support etc..</p>\n\n<h3>Page Code-Behind</h3>\n\n<pre><code>    protected void Page_Load(object sender, EventArgs e)\n    {\n        // Create some controls (BadControl will throw)\n        string goodHtml = SafeLoader.LoadControl(new BadControl());\n        Response.Write(goodHtml);\n\n        string badHtml = SafeLoader.LoadControl(new GoodControl());\n        Response.Write(badHtml);\n    }\n</code></pre>\n\n<h3>Thoughts</h3>\n\n<p>OK, I know what you are thinking, "these controls are instantiated programatically, what about designer support? I spent freaking hours getting these controls nice for the designer, now you\'re messing with my mojo".</p>\n\n<p>OK, so I havent really tested this yet (probably will do in a min!) but the idea here is to override the CreateChildControls method for the page, and take the instance of each control added on the form and run it through the SafeLoader. If the code passes, you can add it to the Controls collection as normal, if not, then you can create erroneous literals or something, up to you my friend.</p>\n\n<h2>Finally..</h2>\n\n<p>Again, sorry for the long post, but I wanted to get the code here so we can discuss this :)\nI hope this helps demonstrate my idea :)</p>\n\n<h2>Update</h2>\n\n<p>Tested by chucking a control in on the designer and overriding the CreateChildControls method with this, works fine, may need some clean up to make things better looking, but I\'ll leave that to you ;)</p>\n\n<pre><code>protected override void CreateChildControls()\n{\n    // Pass each control through the Loader to check\n    // its not lame\n    foreach (Control ctl in Controls)\n    {\n        string s = SafeLoader.LoadControl(ctl);\n        // If its bad, smack it downnnn!\n        if (s == string.Empty)\n        {\n            ctl.Visible = false; // Prevent Rendering\n            string ctlType = ctl.GetType().Name;\n            Response.Write("&lt;b&gt;Problem Occurred Rendering " + \n                ctlType + " \'" + ctl.ID + "\'.&lt;/b&gt;");\n        }\n    }\n}\n</code></pre>\n\n<p>Enjoy!</p>\n'}, {'answer_id': 17871, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 0, 'selected': False, 'text': '<p>I am not sure I understand <a href="https://stackoverflow.com/questions/10793/catching-unhandled-exceptions-in-aspnet-usercontrols#15999">your response</a>.. How are you loading your controls and adding them to your controls collection?</p>\n\n<p>That was the whole point of the bit added in the "Update" section.. You have the flexibility to use the <em>SafeLoader</em> wherever you please.</p>\n\n<p>I am not sure why you feel you don\'t have access/control over the Html? The goal of the SafeLoader is that you dont <em>care</em> what the html is, you simply try and "output" the control (within the "bubble") and determine if it loads OK in its current state.</p>\n\n<p>If it does (i.e. the html is returned) then you can do what you like with it, output the html, add the control to the controls collection, whatever!</p>\n\n<p>If not, then again, you can do what you like, render an error message, throw a custom exception.. The choice is yours!</p>\n\n<p>I hope this helps clarify things for you, if not, then please shout :)</p>\n'}, {'answer_id': 10954250, 'author': 'ThisGuy', 'author_id': 910348, 'author_profile': 'https://Stackoverflow.com/users/910348', 'pm_score': 0, 'selected': False, 'text': '<p>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.</p>\n\n<pre><code>  protected override void Render(System.Web.UI.HtmlTextWriter writer)\n  {\n     try\n     {\n        // Render the module to a local a temporary writer so that if an Exception occurs\n        // the control is not halfway rendered - "it is all or nothing" proposition\n        System.IO.StringWriter sw = new System.IO.StringWriter();\n        System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);\n        base.Render(htw);\n\n        // We made it!  Copy the Control Render over\n        writer.Write(sw.GetStringBuilder().ToString());\n     }\n     catch (System.Exception ex)\n     {\n        string message = string.Format("Error Rendering Control {0}\\n", ID);\n        Log.Error(message, ex);\n        if (Page.IsDebug)\n           writer.Write(string.Format("{0}&lt;br&gt;Exception:&lt;br&gt;&lt;pre&gt;{1}\\n{2}&lt;/pre&gt;", message, ex.Message, ex.StackTrace));\n     }\n  }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/10793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1269/']