How to catch application error outside global.asax ? I want to catch unhandled exception outside global.asax
Asked
Active
Viewed 593 times
1
-
2What's wrong with `global.asax`? – Devin Burke Sep 15 '11 at 17:02
-
1What has this to do with Java? – Ben Robinson Sep 15 '11 at 17:02
-
2And where do you want to catch it, and what do you want to do with it? – John Saunders Sep 15 '11 at 17:04
2 Answers
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
-
-
yes it is working but i want to capture the exception anywhere in the application .right now it is showing in that page only inwhich i wrote above method. – Krishna Yadav Sep 15 '11 at 18:34
-
Right. If you want to capture it anywhere in the application, you'll need to use `global.asax`. Why do you not want to use that? – Devin Burke Sep 15 '11 at 22:48
-
actually i m making server control which logs the error and send it to the db by calling webservice. – Krishna Yadav Sep 20 '11 at 07:39
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

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