views:

835

answers:

5

The questions says everything, take this example code:

<ul id="css-id">
    <li>
    <something:CustomControl ID="SomeThingElse" runat="server" />
    <something:OtherCustomControl runat="server" />
    </li>
</ul>

Now if an error gets thrown somewhere inside these controlls (that are located in a master page) they will take down the entire site, how would one catch these exceptions?

+5  A: 

You can catch all exception not handled elswhere in the Global.asax page / class. Look at:

protected void Application_Error(Object sender, EventArgs e)

method.

Drejc
That will just catch the error, it won't stop it from happening. unless you take corrective action within that method
WebDude
The main goal should be to catch all control related exception whithin the control. The global exception handler should be used as a last line of defense where previous attempts failed. Like for instace the database connection failed or simila
Drejc
+1  A: 

Add a global.asax en implement the Application_Error handler. Use the Server.GetLastError() function to get a handle on the exception thrown.

Maurice
+2  A: 

Unfortunately an unhandled exception will always error your site. YOu can prevent this a few ways though.

  • Use the section in your web.config to show a user friendly message
  • In your Global.asax - or a Custom Handler - catch your unhandled exception and react accordingly - like this

best solution

  • Make sure you controls don't throw unhandled exceptions!
WebDude
+1  A: 

Using the global.asax Application_Error method, as described in How to create custom error reporting pages in ASP.NET by using Visual C# .NET.

An alternative approach would be to use a HTTP module; this gives you some more flexibility (you can handle errors from multiple applications, for example).

mdb
+1  A: 

Do you want to catch the exception and handle it?

Or do you want to prevent the Yellow Screen Of Death? If you are trying to prevent the Yellow Screen Of Death, look at handling the Error event on the HttpApplication (in other words, in your Global.asax).

See the following MSDN page for more details: http://msdn.microsoft.com/en-us/library/system.web.httpapplication.error.aspx

Specifically this paragraph:

The exception that raises the Error event can be accessed by a call to the GetLastError method. If your application generates custom error output, suppress the default error message that is generated by ASP.NET by a call to the ClearError method.

Brannon