ASP.NET provides several levels at which you can handle and respond to errors that may occur when you run an ASP.NET
application. ASP.NET provides three main methods that allow you to trap and respond to errors when they
occur: Page_Error, Application_Error, and the application configuration file (Web.config).
1. In Page
public void Page_Error(object sender,EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Page_Error event
" +
"
Error in: " + Request.Url.ToString() +
"
Error Message: " + objErr.Message.ToString()+
"
Stack Trace:
" +
objErr.StackTrace.ToString();
Response.Write(err.ToString());
Server.ClearError();
}
2.In Global.asax
using System.Diagnostics;
protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Application_Error eventn" +
"Error in: " + Request.Url.ToString() +
"nError Message:" + objErr.Message.ToString()+
"nStack Trace:" + objErr.StackTrace.ToString();
EventLog.WriteEntry("Sample_WebApp",err,EventLogEntryType.Error);
Server.ClearError();
//additional actions...
}
3. Web.config
Modes in web.config:-
On: Unhandled exceptions redirect the user to the specified defaultRedirect page. This mode is used mainly in production.
Off: Users receive the exception information and are not redirected to the defaultRedirect page. This mode is used mainly in development.
RemoteOnly: Only users who access the site on the local computer (by using localhost) receive the exception information. All other users are redirected to the defaultRedirect page. This mode is used mainly for debugging.