Reputation: 5234
I am trying to log all "general errors" from the site I am maintaining, to debug the code-behind, without having to show the detailed error page to the users. The web.config
says:
<customErrors mode="RemoteOnly" defaultRedirect="~/GeneralError.html"/>
which works for problems like divide by zero, null-reference exceptions, missing dll, etc. After lots of reading here I found that these are the "unhandled exceptions", but do not reach the handler Application_Error()
in global.asax
. What does work, on a per-page basis, is:
protected override void OnError(EventArgs e)
{
Exception TheException = Server.GetLastError();
// todo: log the exception to the database
base.OnError(e); //pass the exception to the regular handler
return;
}
But could this be changed to log the unhandled exceptions of all pages with a single method? How can I overwrite, or modify, the base class Page
?
I also thought of put logging in the code-behind of GeneralError.aspx
, but then there would be no stack trace or exception message, and also any user may call this page directly just to annoy us.
I investigated using some IErrorHandler
interface mentioned in some posts, but this should relate to WinForm apps, not to asp.net web apps.
Upvotes: 0
Views: 733
Reputation: 5234
I am currently studying https://msdn.microsoft.com/en-us/library/aa479332.aspx, found through https://stackoverflow.com/a/138088/1845672 which talks about exactly my problem with the exact same approach: provide a solution to log errors on all pages in a maintainable way without modifying all pages.
The download link on the microsoft site is stale. According to: https://code.google.com/p/elmah/issues/detail?id=64 the sources are moved from the microsoft site to: elmah.googlecode.com/files/GDN-ELMAH-1.0.5527-setup.zip .
Looks like this is a complete solution . . .
Upvotes: 0
Reputation: 454
Create a new class:
public class MyPage : System.Web.UI.Page
{
protected override void OnError(EventArgs e)
{
Exception TheException = Server.GetLastError();
// todo: log the exception to the database
base.OnError(e); //pass the exception to the regular handler
return;
}
}
and instead of inheriting from System.Web.UI.Page inherit from MyPage on your individual pages.
Upvotes: 0
Reputation: 4331
Use the Application_Error method in your Global.asax file.
Inside your Application_Error method implementation call Server.GetLastError(), log the details of the exception returned by Server.GetLastError().
Exception LastError;
String ErrMessage;
LastError = Server.GetLastError();
if (LastError != null)
ErrMessage = LastError.Message;
else
ErrMessage = "No Errors";
Response.Write("Last Error = " + ErrMessage);
See here at MSDN or if you want a complete Microsoft Example at Complete Example for Error Handlers.
Upvotes: 2