Wednesday, October 14, 2009

Enterprise Library - Exception Handling and Logging

Exception handling is one of the key points in any Application. Exception should be handled such that we have to know the source of exception clearly and we can directly point the issue. Whatever exceptions raised first we have to save it some place. This is can be handled using "Logging Application Block" of Enterprise Library.

Exceptions can be of any type. Suppose you want to log only SQL Exceptions. This is can also be done.

First step of Exception handling and Logging, is creating of Exception Handling Application block.

After creating a exception handling application block.

Now right click Exception Handling Application Block -> New -> Exception Policy
Now change the name to a meaningful name. I have given it as "LogPolicy".
Now right click "LogPolicy" -> New -> ExceptionType.
It will display a list of exception which are to be handled by "LogPolicy".


I have choosen "Exception", its obvious that it will handle any exception.
Now right click "Exception" -> New -> Logging Handler

Now click "logging handler" -> Formatter Type
Here I choose the TextExceptionFormatter


Now click "Log Category" -> U will a drop down which points to the Logging Application Block -> Category Sources-> General - Select it

Under Logging Application Block -> Special Sources -> Logging Errors & Warnings -> Formatted Eventlog TraceListener tells that the Logging is done to System Event Viewer - Application

Upon saving this as Web.config or App.config, Enterprise library configuration will generate respective XML in it.

Using it Code:
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Logging;

try
{

}
catch (Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "LogPolicy");
if (rethrow)
throw;
return;
}