Logging an Exception
In addition to handling exceptions, you can also configure the exception handling block to log the exceptions. As mentioned previously, the Exception Handling Block accomplishes this with the help of the Logging Block. To demonstrate logging, add another button named
btnLogException and modify its
Click event as follows:
private void btnLogException_Click
(object sender, EventArgs e)
{
try
{
throw new Exception
("This is a test exception");
}
catch (Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException
(ex, "Log Only Policy");
if (rethrow)
{
throw;
}
}
}
The
catch block above invokes the
ExceptionPolicy.HandleException method by passing the exception object (
ex) as well as the policy (the "Log Only Policy" in this case) as arguments. Similar to the exception policies, you also specify logging configuration information in the
app.config or
web.config file. For example, the
app.config code shown below configures the "Log Only Policy" as a child element of the
<exceptionPolicies> element:
<add name="Log Only Policy">
<exceptionTypes>
<add name="Exception"
type="System.Exception, mscorlib,
Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089"
postHandlingAction="None">
<exceptionHandlers>
<add logCategory="Default Category"
eventId="100" severity="Error"
title="Exception Management
Application Exception"
priority="0"
formatterType="Microsoft.
Practices.EnterpriseLibrary.
ExceptionHandling.TextExceptionFormatter,
Microsoft.Practices.EnterpriseLibrary.
ExceptionHandling"
name="Logging Handler"
type="Microsoft.Practices.EnterpriseLibrary.
ExceptionHandling.Logging.
 | |
| Figure 3. Event Log Entry: The figure shows a sample application log message as seen through the Windows Event Viewer. |
LoggingExceptionHandler,
Microsoft.Practices.EnterpriseLibrary.
ExceptionHandling.Logging"/>
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
The
app.config file that you'll find in the
downloadable sample code for this article contains an additional example. For example purposes, the Logging Block simply logs the exceptions in the Windows Application Log, as shown in
Figure 3.
Note that the logging configuration information in the
app.config file controls the formatting of the log entry.
As you have seen from this article, the exception handling block obviates the need to write the exception handling plumbing code by providing a set of highly reusable classes for handling, logging and processing exceptions. By using these classes, you can reduce errors, bugs, and typos in your application and focus on the core business logic of the application thereby increasing productivity.