Saturday, January 1, 2011

Exception handling and logging

Exception - Is an unusual occurance in the logic of the application, eg: divide by zero, reading corrupted file.. etc.
Exception Handling - Managing these exceptions in order to make sure that it does not stop application from running and not distirbing the end user
Exception Handling Methods
1. Structured Exception Handling (try-catch-finally-throw)
eg:
try
{
throw new System.IO.FileNotFoundException;
}
catch(System.IO.FileNotFoundException)
{}
catch(System.UnauthorizedAccessException)
{}
catch(Exception ex)
{}
finally
{}

2. Using Error Events
Error events can be used against exception that were not foreseen or handled elsewhere.
Page_Error - Page level
Global_Error - Global.asax
Application_Error - Global.asax
To get the last error occured in the application use Server.GeLastError() and to clear the excpetions use Server.ClearError()
GetLastError() can be used only before redirecting to a new page.

3. Using Error Pages
This is a high level way of handling exceptions especially for application wide errors which are outside the scope of code. For eg: to handle IIS errors like 404 Page Not Found

There are 3 ways of using it:
a) Specify Error Pages corresponding to Error Code in IIS itself. Exceptions registered with IIS can be seen from custom errors section of application properties.
If we are redeploying the application in IIS, we have to redo these settings all over again.

b) Specify error pages in CustomErrors tag in web.config
<customerrors defaultredirect="1.aspx" mode="on">
<error redirect="Error.aspx" statuscode="404">
</customerrors>
mode ="on" - To view error pages while running locally
mode="RemoteOnly" - To view error pages when ru
nning from client
Error page type should be supportable by asp.net

c) Specify Error page in ErrorPage attribute of Page

Because of redirection, context for error is lost, Server.GetLastError() returns nothing

Tracing
Tracing is used for logging exceptions
How to enable tracing in .net...

This will write the trace at the end of each file.
To write the trace in to a file;
pageOutput="false"
requestLimit="20" - This will restrict the tracing for the first 20 requests
To enable tracing at the page level - trace="true"

No comments:

Post a Comment