1) Page Level
2) Application Level
3) Through Web.Confing
1) Page Level Error Handling :
We can handle error at page level so that if any error comes under the page scope it will handle through the OnError Method of page, But its only at page level not outside that scope. Whenever we create a web form its class drive from System.Web.UI.Page and that why page object help us to invoke page level error. What we do we override OnError method of the page. Like
protected override void OnError(EventArgs e)
{
Exception objException = Server.GetLastError (); // Return Current Exception
string errorDescription =
"Source of Error:" + objException.Source +
"Message : " + objException.Message +
"Stack trace: " + objException.StackTrace;
Response.Write (errorDescription); // Or you can log the Error or redirect to somewhere else/
}
2) Application Level Error Handling :
Another approach for error handling is at application level. Whenever any Error comes Application_Error sub called. Its a good place for handling error because no need to write it on every page. It Works something like that:
void Application_Error(object sender, EventArgs e)
{
Exception objException = Server.GetLastError (); // Return Current Exception
string errorDescription =
"Source of Error: " + objException.Source +
"Message : " + objException.Message +
"Stack trace: " + objException.StackTrace;
// After that use that Error errorDescription as you want eithr make log or redirect to somewhere else/
}
3) Web.Config Custom Errors
Third place is Web.Config, it enables us to configure html error pages to be displayed in place of a error stack trace Yellow page(really developer hate this). Through it we can handle error on specific code or we can create a single page for handling all the Error.
When we create a new website it looks like
Here we have mode attribute which can be "On|Off|RemoteOnly"
"RemoteOnly" options is the default option. Specifies that custom errors are shown only to remote clients, and ASP.NET errors are shown to the local host
"On" option shows custom errors are enabled.
"Off" Specifies custom errors are disabled.
We can handle errors based on specific code like that:
< customErrors mode="On" >
< error statusCode="403" redirect="NoAccess.htm" />
< error statusCode="404" redirect="FileNotFound.aspx" />
< error statusCode="500" redirect="GenericErrorPage.htm"/>
or We can use a single page redirect for all the Errors
< customErrors mode="On" defaultRedirect="ForAllError.htm" />
Stay away from Errors now
Keep Happy and Programming:)
No comments:
Post a Comment