1

How to catch application error outside global.asax ? I want to catch unhandled exception outside global.asax

Devin Burke
  • 13,642
  • 12
  • 55
  • 82
Krishna Yadav
  • 33
  • 1
  • 3
  • 8

2 Answers2

1

Each page derives from System.Web.UI.Page. You can override each individual page's OnError method like this:

protected override void OnError(EventArgs e)
{
    // Capture the exception.
    var exception = HttpContext.Current.Server.GetLastError();

    // Create an error message.
    var errorInfo = 
       "<br/>URL: " + HttpContext.Current.Request.Url.ToString() +
       "<br/>Source: " + exception.Source + 
       "<br/>Message: " + exception.Message +
       "<br/>Stack trace: " + exception.StackTrace;

    // Write out the error message. You can do whatever you want with it.
    HttpContext.Current.Response.Write(errorInfo);

    // Clear the error that you handled from the cache so it's not read again.
    HttpContext.Current.Server.ClearError();

    // Perform the normal operations that would happen if you didn't override.
    base.OnError(e);
}
Devin Burke
  • 13,642
  • 12
  • 55
  • 82
0

Yes there are several places including on the page with page_error check out: http://msdn.microsoft.com/en-us/library/aa479319.aspx

Also look at elmah for error logging

http://code.google.com/p/elmah/

Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
  • Hiii, Thanks for helping me . elmah is really good. i m catching exception and passing it to a webservice but webservice is not taking exception as an object it is showing some serializable error.i want to catch the exception and send it to the db using webservice .Please help me regarding this.. – Krishna Yadav Sep 20 '11 at 07:31
  • thats a different question than posted and really should warrant another question - but since its fairly easy: http://stackoverflow.com/questions/486460/how-to-serialize-an-exception-object-in-c note you can do this in two ways either create a new exception class that is [serializable] or use NetDataContractSerializer on the exception as is done here: http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/83ceb6bd-83c8-4106-abe5-04431668be48/ – Adam Tuliper Sep 20 '11 at 14:54
  • I am dragging an server control from toolbox into another webapplication,and i want to add a line in that Webapplications web.config file automatically . Please help me .. – Krishna Yadav Oct 10 '11 at 06:07