Brief description of the Enterprise Library Exception Handling block in. NET 2.0

Source: Internet
Author: User
Tags configuration settings define exception mscorlib
Prepared by Xie Qidong

The Enterprise Library Exception Handling block provides all the basic code required to handle exceptions. Now, you do not need to write these repetitive Exception Handling codes, you only need to simply use them in the program to ensure consistent and efficient exception handling.

In an ideal program world, all the code you write runs correctly, but the reality is that no matter how careful you are when writing code, errors will always happen, you must have an efficient and configurable framework to handle errors in an "elegant" way. In addition, you must understand that, people usually measure the effectiveness of an exception handling based on the impact on the user experience of the program. Therefore, a good Exception Handling solution not only allows users to handle errors elegantly, but also allows developers or system administrators to handle configurable errors, robust configuration settings are provided, which is also a key component of the exception handling block.

Along with Enterprise Library 2.0, the new exception handling application block has been greatly improved since the release of the old Exception management application block, you can download the entlib caching block from msdn. For effective use, you must accept the following three main points:

· Exception handling is a process of handling exceptions when your code detects exceptions.

· Exception logging records an exception process, including sending and formatting exceptions to the event recorder or sending an e-mail, while Exception Handling blocks use logging and event logging.

· The Exception Handling Policy allows you to control exception handling and use external configuration file records. The advantage is that you do not need to implement such rules in the Code. In other words, you can define Exception Handling in a policy file, and then modify the behavior during testing, debugging, and product finalization without changing the code to meet different Exception Handling needs.

In addition, when an exception processing block is used, the following three tasks can be performed when an exception is detected:

· You can encapsulate exceptions as 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 attribute.

· You can replace the original exception with a new exception. In general, the purpose of doing so is not to let the detailed information of the original exception pass out the program.

· You can record exceptions. Of course, you can also use a wrapped or replaced method to achieve this purpose, or you can record the original exception and pass it to the call stack.

  Use Exception Handling Block

After installing the Enterprise Library, you can use the exception handling block to write code. to correctly use the exception handling block, follow these steps:

1. Add a pair to Microsoft in your solution. practices. enterpriselibrary. common. DLL and Microsoft. practices. enterpriselibrary. exceptionhandling. DLL Assembly reference, you can use the "add reference" option, and go to the X:/program files/Microsoft Enterprise Library January 2006/bin folder, if you want to use Exception Processing log records, please add another pair to Microsoft. practices. enterpriselibrary. exceptionhandling. logging. DLL reference.

2. Add necessary projects to your app in <configsections> under the root <configuration>, as shown below. config (Windows Forms) or web. config (Asp.. Net Program) file.

<Section
Name = "exceptionhandling"
Type = "Microsoft. practices.
Enterpriselibrary.
Exceptionhandling.
Configuration.
Exceptionhandlingsettings,
Microsoft. practices.
Enterpriselibrary.
Exceptionhandling "/>

3. If you are handling a log with an exception, you must add the following settings in <configsections>.

<Section
Name = "loggingconfiguration"
Type = "Microsoft. practices.
Enterpriselibrary. logging.
Configuration. loggingsettings,
Microsoft. practices.
Enterpriselibrary. Logging "/>

4. Next, add <exceptionhandling> directly under <configuration>. Within <exceptionhandling>, you can add all the exception handling policies. 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,
Predictionmgmtblockexample "/>
</Exceptionhandlers>
</Add>
</Exceptiontypes>
</Add>
</Exceptionpolicies>
</Exceptionhandling>

The preceding settings specify a policy for handling all exceptions. In addition, you can use the <exceptionhandlers> item to specify a custom exception handling method, which will handle the exception in an appropriate way. In this example, the custom exception handling method is implemented as an appmessageexceptionhandler class. in the later part of this article, we will see the specific implementation of the appmessageexceptionhandler class. The posthandlingaction attribute specifies the action to handle policy-based exceptions. This attribute accepts the following values: None, policyrethrow, and thrownewexception.

The simplest way to add these settings is to use the Enterprise Library Configuration tool in the Enterprise Library. In the Enterprise Library Configuration tool, set 1 above.


Figure 1

5. Introduce the core namespace of the exception handling block in your project "Microsoft. Practices. enterpriselibrary. exceptionhandling ".

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

Use the exceptionpolicy class

As long as an exception handling block is used, it must deal with the exceptionpolicy class. The static method named handleexception () that is derived from it allows the client program to interwork with the exception handling block, the policy can be provided as a parameter here. The handleexception () method uses a class factory to create the exceptionpolicyimpl type object for the corresponding policy, while the exceptionpolicyimpl object has a exceptionpolicyentry object set-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 and implements the iexceptionhandler interface. When a policy is executed, the object set provides the sequence used by exception handling blocks. Each object that implements the iexceptionhandler interface is associated with the type corresponding to each processing method.

The exception handling method is.. Net class, which encapsulates 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:

· Packaging handling method: this exception handling method encapsulates another exception with one exception.

· Replace handling method: this exception handling method replaces another with one exception.

· Log record handling method: this exception handling method formats the exception information, such as notification and stack tracking. The log record processing method registers the information into the log block for future verification.

If you need to implement your own processing method, you can use the enterprise database configuration tool to expand the exception handling block on your own. The biggest benefit of this is that you don't have to modify and rebuild the entire program just to expand it.

  Use exceptionpolicy to handle exceptions

To demonstrate the use of exception handling blocks, the following is a simple example, for example, a simple windows form program named exceptionmgmtblockexample. Create this project in Visual Studio, add the reference mentioned above, open the default form in the Form Designer, add a command button named btnhandleexception, and modify the 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 the try block, only an exception is thrown, and the Catch Block will catch it and trigger the handleexception () method in the exceptionpolicy class, A policy name parameter "golbal policy" is passed in. As mentioned in the previous section, "golbal policy" is associated with the exception handling method named appmessageexceptionhandler. Its declaration is 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, 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, while the handleexception method triggers another method named showthreadexceptiondialog, which will format the exception information and display it on the screen.

If you run this program and click "handle exception", the message box shown in Figure 2 is displayed.


Figure 2

  Record an exception

In addition to exception handling, you can configure Exception Handling blocks to record exceptions. As mentioned above, you can do this with the help of logging blocks. To demonstrate 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 the exception object (Ex) and Policy (log only policy in this example), the catch block will trigger the exceptionpolicy. the handleexception method is similar to the exception policy. config or web. the configuration information is specified in the config file, for example, the app shown below. the Config code configures "log only policy" as a subitem 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 = "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.
Loggingexceptionhandler,
Microsoft. Practices. enterpriselibrary.
Exceptionhandling. Logging "/>
</Exceptionhandlers>
</Add>
</Exceptiontypes>
</Add>

For the purpose of demonstration, the logging block simply records exceptions in the "application" item, as shown in 3.


Figure 3

Note that the logging configuration information in the app. config file controls the log item format.

As you can see in this article, the exception handling block provides a set of highly reusable classes, so you do not have to repeat the code for operations, processing, and recording exceptions; by using these classes, you can reduce errors and bugs in the program, save time for typing input, and focus on the core business logic of the program, thus greatly improving productivity.

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.