An overview of Enterprise Library exception handling blocks in. NET 2.0

Source: Internet
Author: User
Tags bool config configuration settings error handling exception handling implement mscorlib visual studio
Exception handling Enterprise Library exception handling blocks (Enterprise Library Exception handling block) provide all the basic code needed to handle exceptions, and now you can no longer write these repetitive exception handling code simply by using them in your program, To ensure consistent and efficient exception handling.

In an ideal program world, all the code written is run correctly, but the reality is, no matter how carefully you write code, errors always happen, so you have to have an efficient, configurable framework to handle errors in an "elegant" way, and you must understand that People usually measure the effectiveness of an exception handling by how much it affects the user experience of the program. Therefore, a good exception handling solution is not only "gracefully" handling errors from the user's point of view, but also provides robust configuration settings through a developer or system administrator with configurable error handling, which is also a key component of the exception handling block.

Together with Enterprise Library 2.0, the new exception handling Application block, which has been greatly improved since the release of the old exception Management Application Block, is available from the MSDN download EntLib Caching. For effective use, you must accept the following three main points of view:

• Exception handling is the process of handling an exception when your code detects an abnormal occurrence.

• Exception logging is the process of recording an exception, which includes sending formatting exceptions to the event logger or sending an e-mail message, while exception-handling blocks take advantage of logging and event logging.

• Exception handling policies allow you to control exception handling and the behavior of using external configuration files to record the advantage of this is that you don't need to implement such a rule in your code now, in other words, you can define exception handling in a policy file, and then, without changing the code, test, Debug, Modify behavior during product stereotypes to accommodate different exception handling needs.

In addition, with exception handling blocks, the following three things can be done when an exception is detected:

• You can wrap the exception into a new exception and add new context information or error details. When a new exception is passed to the call stack, the original exception can still be accessed through the InnerException property.

• You can replace the original exception with a new exception. In general, the purpose of this is not to let the details of the original exception pass through the program.

• You can record exceptions. Of course, this can be achieved either by using a wrapper or a replacement method, or you can record the original exception and pass it to the call stack.

   using exception handling blocks

After installing the Enterprise Library (Enterprise library), you can begin writing code with exception handling blocks, following these steps to properly use exception handling blocks:

1, Add a separate pair of Microsoft.Practices.EnterpriseLibrary.Common.dll and MICROSOFT.PRACTICES.ENTERPRISELIBRARY.EXCEPTIONHANDLING.D to your solution ll assembly reference, you can use the Add Reference option and navigate to the X:\Program Files\Microsoft Enterprise Library January 2006\bin folder, if you also want to use exception handling logging, Please add another reference to the Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll.

2, as shown below, add the necessary items to your app.config (Windows Forms) or web.config (asp.net program) file under Root <configuration>.

<section
Name= "ExceptionHandling"
Type= "Microsoft.practices.
Enterpriselibrary.
ExceptionHandling.
Configuration.
Exceptionhandlingsettings,
Microsoft.practices.
Enterpriselibrary.
ExceptionHandling "/>
3. If you use logging with exception handling, you also need to include the following settings in <configSections>.

<section
Name= "Loggingconfiguration"
Type= "Microsoft.practices.
Enterpriselibrary.logging.
Configuration.loggingsettings,
Microsoft.practices.
Enterpriselibrary.logging "/>
4, Next, directly under <configuration> add <exceptionHandling>, within <exceptionHandling>, you can add all the exception handling policy, the following code, Indicates that a policy named "Global Policy" is specified in <exceptionHandling>.

<exceptionHandling>
<exceptionPolicies>
<add name= "Global Policy"
<exceptionTypes>
<add name= "Exception"
Type= "System.Exception,
mscorlib, version=2.0.0.0,
Culture=neutral,
publickeytoken=b77a5c561934e089 "
Posthandlingaction= "None" >
<exceptionHandlers>
<add name= "Application
Message Handler "
Type= "Exceptionmgmtblockexample.
Appmessageexceptionhandler,
Exceptionmgmtblockexample "/>
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
The above settings specify a policy that handles all exceptions. In addition, using <exceptionHandlers> items, you can specify a custom exception-handling method that handles exceptions in an appropriate manner. In this example, the custom exception handling method is implemented as a class named Appmessageexceptionhandler, and in the later part of this article, you will see the implementation of the Appmessageexceptionhandler class. Property posthandlingaction Specifies the behavior of handling policy-based exceptions, which accept the following values: None, Notifyrethrow, Thrownewexception.

The easiest way to add these settings is to use the Enterprise Library Configuration tool (Enterprise Library Configuration Tool) in the Enterprise Library, as shown in Figure 1 in the Enterprise Library Configuration tool.


Figure 1


5, in your project to introduce the exception processing block core namespace "Microsoft.Practices.EnterpriseLibrary.ExceptionHandling".

6. Now, you can use the classes in the namespaces above to write code.

   using the Exceptionpolicy class

As long as you use exception handling blocks, you have to deal with the Exceptionpolicy class, and the static method named HandleException () allows the client program to interact with the exception-handling block, where the policy can be provided as a parameter. The HandleException () method uses a class factory to create Exceptionpolicyimpl type objects for the corresponding policy. The Exceptionpolicyimpl object has a set of Exceptionpolicyentry objects-that is, in the configuration file of the corresponding policy, each exception type corresponds to an object. For each exception type, the Exceptionpolicyentry object contains an object set that implements the Iexceptionhandler interface, and when the policy is executed, the set of objects provides the sequence used by the exception-handling block , and each object that implements the Iexceptionhandler interface is associated with the type that corresponds to each processing method.

The exception handling method is. NET class, which wraps the exception handling logic and implements the Iexceptionhandler interface defined in the exception handling block, by default, the exception handling block contains the following three exception handling methods:

• Packing Handling method: This exception handling method wraps another exception with an exception.

• Substitution Processing Method: This exception-handling method replaces another exception with an exception.

• Logging Processing method: This exception-handling method formats exception information, such as notifications and stack traces. The logging method registers the information in the log block for future verification.

If you need to implement your own processing methods, you can also extend exception handling blocks by using the Enterprise Library Configuration tool. The great thing about this is that you don't have to modify and reconstruct the entire program just to expand it.

   using Exceptionpolicy to handle exceptions

To demonstrate the use of exception handling blocks, here is a simple example, such as a Windows Form program named Exceptionmgmtblockexample. Create this project in Visual Studio, add the references mentioned earlier, open the default form in the Form designer, add a command button named Btnhandleexception, and modify its Click event as follows:

private void Btnhandleexception_click (object sender, EventArgs e)
{
Try
{
throw new Exception ("This is a Test Exception");
}
catch (Exception ex)
{
BOOL rethrow = Exceptionpolicy.handleexception (ex, "Global Policy");
if (rethrow)
{
Throw
}
}
}
In a try block, simply throws an exception, and the catch block catches it, triggering the HandleException () method in the Exceptionpolicy class and passing a policy name parameter of "Golbal Policy" in it. As mentioned in the previous section, "Golbal Policy" is associated with an exception-handling method named Appmessageexceptionhandler, which is declared as follows:

Using System;
Using System.Collections.Specialized;
Using System.Windows.Forms;
Using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
Using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
Using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
Using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;

Namespace Exceptionmgmtblockexample
{
[ConfigurationElementType (typeof (Customhandlerdata))]
public class Appmessageexceptionhandler:iexceptionhandler
{
Public Appmessageexceptionhandler (NameValueCollection ignore)
{}
Public Exception handleexception (Exception Exception, Guid Correlationid)
{
DialogResult result = this. Showthreadexceptiondialog (Exception);
if (result = = Dialogresult.abort)
Application.exit ();
return exception;
}
Private DialogResult Showthreadexceptiondialog (Exception e)
{
String errormsg = e.message + Environment.NewLine + Environment.NewLine;
Return MessageBox.Show (errormsg, "Application Error", MessageBoxButtons.OK, Messageboxicon.stop);
}
}
}
As you can see, the custom exception handling method inherits from the Iexceptionhandler interface, and the HandleException method triggers another method named Showthreadexceptiondialog. It formats the exception information and displays it on the screen.

If you run this program and click the "Handle Exception" button, you will see the message box shown in Figure 2.


Figure 2
   Log an exception

In addition to handling exceptions, you can configure exception handling blocks to record exceptions. As mentioned earlier, this work can be done with the help of the log block (Logging blocks), for a demo of logging, add a 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
}
}
}
By passing exception objects (ex) and policies (in this case log only Policy), The catch block will trigger the Exceptionpolicy.handleexception method, similar to the exception policy, where you can specify the record configuration information in the app.config or Web.config file, for example, the app.config code shown below Log only Policy is configured with a subkey under <exceptionPolicies>:

<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= "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.
Loggingexceptionhandler,
Microsoft.Practices.EnterpriseLibrary.
Exceptionhandling.logging "/>
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
As a demonstration, the log block simply records the exception in the application item, as shown in Figure 3.


Figure 3
Note that the record configuration information in the app.config file controls the format of the log entry.

As you can see from this article, the exception handling block provides a set of highly reusable classes, this eliminates the need to rewrite the code to manipulate, process, and record exceptions, by using these classes, you can reduce bugs, bugs, and time to save typing, and focus on the core business logic of the program. Thus, productivity can be greatly improved.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.