0

I have an ASP.NET page with lots of event handlers that look like this:

Private Sub btnNextEvent_Click(sender As Object, e As EventArgs) Handles btnNextEvent.Click
    Try
        NextRegistration()            
    Catch ex As Exception
        lblError.Text = ex.Message
    End Try
End Sub

That tiny try-except block is repeated in many (maybe a dozen) places.

Is there a way to define a page-wide "default" exception handler, so that I could say something like this?

Private Overrides Sub DefaultHanderIWishIHad(ex As Exception)
    lblError.Text = ex.Message
End Sub

Private Sub btnNextEvent_Click(sender As Object, e As EventArgs) Handles btnNextEvent.Click
    'no need to handle here, because the default handler is just fine...
    NextRegistration()            
End Sub
JosephStyons
  • 57,317
  • 63
  • 160
  • 234
  • You seriously want to put the exception message into a label? What are you using this for? Troubleshooting? That won't be so easy without the full exception trace. Try putting `ex.ToString()` into the label. – John Saunders Apr 10 '13 at 18:53
  • This example is simplified for the sake of discussion. For debugging, I am just putting the error in a label. – JosephStyons Apr 10 '13 at 18:56
  • I'd suggest, for debugging or anything else, use [ASP.NET Health Monitoring](http://msdn.microsoft.com/en-us/library/bb398933.aspx), then just remove those try/catch blocks. – John Saunders Apr 10 '13 at 18:58

3 Answers3

0

On a page

private void Page_Error(object sender, EventArgs e)
{ /* ... */ }

Application: Global.asax

void Application_Error(object sender, EventArgs e)
{ /* ... */ }
Peter Kiss
  • 9,309
  • 2
  • 23
  • 38
0

Even you can use the ELMAH http://code.google.com/p/elmah/ . Which is good and easy to configure and handle all the unhandled exception

Devesh
  • 4,500
  • 1
  • 17
  • 28
0

Actually if you get an exception and not handle on place, then you lose the control - and from there you can only redirect and log the error.

So I do not recommended to have a global error catching. Now on page there is a function that is called on exceptions, the OnError, but I only suggest it for close any open handlers, and not for handling any error, because as I say, when you are there you have lose the control of your page.

protected override void OnError(EventArgs e)
{
   base.OnError(e);
}

relative: How do I make a "generic error" page in my ASP.NET application so that it handles errors triggered when serving that page itself?

Community
  • 1
  • 1
Aristos
  • 66,005
  • 16
  • 114
  • 150