Enterprise Library Exception Handling Application Block Development Task details

Source: Internet
Author: User
This document is maintained at: http://wiki.entlib.net.cn/entlibhelp31exceptionhandlingapplicationblock.ashx.

This topic discusses different aspects of the Plan Exception Handling Policy. It is divided into three aspects:

    • Determine appropriate exception policies and activities
    • Specify different processing activities based on exception types and policies
    • Send an exception to an exception handling ApplicationProgramBlock

3.1-determine appropriate exception policies and activities

This information is taken from the exception management architecture guide. For the complete design and implementation guide for creating an exception management system using. NET technology, see that document.

To build a successful, flexible, easy-to-maintain, and supported application, you must use appropriate policies for exception management. You must set the system to ensure that it can complete the following events:

    • Detect exceptions
    • Record logs and report information

Generate events that can be monitored externally to help the system operate

If you spend time designing a clear and consistent Exception management system at the beginning, it will free you from having to piece together the system during development, or just as bad, from having to re-handle exceptions to existing onesCodeThe Foundation.

Differences
The common management system must be well encapsulated and the log and report details must be decoupled from the application's business logic. It must also be able to generate standards that can be monitored by the operator to provide the current health of the application
And status. This helps you create applications that can quickly and accurately notify the operator of issues occurring in the task. It also provides valuable information to help developers and Support Services solve problems.

Exception Handling process and Exception Handling Application Block

Figure 1 shows the basic steps for the application to complete exception handling.

Figure 1: exception handling process

Every method and process in the application code follows this process to ensure that exceptions are handled in the appropriate context environment, and the Environment is defined by the scope of the current method. This process will continue to occur when an exception occurs along the call stack.

When to capture exceptions

The method only captures exceptions when it has executed one or more of the following activities:

    • Collects logs.
    • Add any related information to the exception.
    • Run the clear code.
    • Try to recover.

If one or more of these activities are not executed for a specific method, the method does not capture exceptions. Instead, it will spread up the call stack. It keeps the code clean and clear, because each method only captures exceptions that must be handled within the scope of a specific method, and allows all other exceptions to continue propagation.

Exception Propagation

There are three main methods to spread exceptions:

    • Enable Automatic propagation of exceptions. In this way, you can ignore exceptions without doing anything. This causes the control to immediately move up from the current code along the call stack until the capture block of the filter found using the configured exception type.
    • Capture and throw an exception again. This method captures and acts on exceptions and cleans up or completes any other necessary processing within the scope of the current method. If you do not recover from an exception, the same exception will be thrown again to the caller.
    • Capture, package, and then throw the packaging exception. If an exception is propagated up the call stack, the correlation of the exception type is reduced. When an exception is encapsulated, more related exceptions are returned to the caller. This is shown in figure 2.

Figure 2: propagation exception

This method can be used to capture exceptions. This allows you to handle exceptions, clean up, or execute any other processing required in the current method range. If the exception is not restored, the exception is encapsulated into a new exception and a new exception is thrown to the caller.ExceptionClassInnerexceptionThe property explicitly allows you to retain the previous caught exception. This allows the original exception to be encapsulated in one or more related external exceptions as internal exceptions.InnerexceptionAttribute is set in the constructor of the exception class.

When you use an exception Processing Application Block, you can use the configured policy to spread the exception. For more information about configuration policies, see enter configuration information.

Hide exception information

For Web Services exposed to external companies and systems, you may not want to expose all the exception information to the client. Exceptions will be thrown to the client for processing, but they may not want to send details of each exception to the outside of the company. You may want to throw an exception that only indicates that the service is faulty.

In
In this case, you can create a general application that contains the information you want to transmit. In the Web
When the server captures unprocessed exceptions, it will record the exception logs, complete any necessary processing, and then construct a new instance for general application exceptions. Then, you can set any desired message in the abnormal general application.
And throw it to the client. This allows you to record detailed log information in the Web Service and throw an exception without details to the client.

When you use an exception handling Application Block, use the replacement handler to hide the exception message. For more information about hiding the exception information, see replacing the exception scenario.

Notification

Notifications are an important component of any exception management system. Logs are important to help you understand what errors are and what problems must be corrected, but the relevant conditions of the notification are put first. If no correct notification is provided, exceptions cannot be detected.

The notification processing adapted to the application must be decoupled from the application code. You do not need to modify the code every time you modify the notification mechanism, for example, when modifying the recipient list. Applications must contact error conditions and rely on decoupled monitoring systems to identify errors and take appropriate actions.

If the application does not run in the environment using the monitoring system, you can create a notification from the application. One way is to work closely with any operator or monitoring system developer to define the normal process of monitoring and sending notifications.

When Exception Handling application blocks are used, custom handlers are used to notify users. For more information, see notification user scenarios.

Plan for Exception Handling

After defining the architecture of the application, you will determine how to handle exceptions generated by the application. The policy meets all security, confidentiality, and performance requirements. The general guidelines for exception handling policies are as follows:

    • Do not catch exceptions unless some value types can be added. In other words, if the knowledge about exceptions is useless to users, you, or applications, do not capture them.
    • If you want to retry the operation, add the information to the exception, hide the sensitive information contained in the exception, or display the formatted Information, the exception will be caught.
    • Generally, exceptions are handled only on application boundaries (such as the top layer of the logic layer, the layer, the boundary of the service, or the UI Layer. Also, replace sensitive information with exceptions that include information that can be safely used outside the current boundary.
    • Do not spread sensitive information across trust boundaries. This is a standard security consideration, but it is often ignored when handling exception information. Replace the exception containing sensitive information with a new exception that contains information that can be safely used outside the current boundary.
    • An exception is generated as accurately as possible, and the specified action can be performed when the exception is triggered. In some cases, you may need to write custom exceptions that use the required attributes.
    • The error messages displayed to the user should be related and suggestions for correction activities are provided. In most cases, the error information displayed to the user does not include sensitive information, such as stack tracing and server name.

3.2-specify different handling activities based on exception types and policies

The exception handling Application Block separates the definition of how to handle exceptions (that is, the exception Policy) from the application code that uses the application block to handle exceptions. Use the configuration console to create and name policies.

By using the exception policy, the application can change without modifying the application code in response to exceptions.

Configure an exception Policy

You can use the configuration console to create an exception handling policy. An exception policy has a name and constructs a set of exception types processed by the policy. Each exception type has a list of sequentially executed handlers.

I
Applications can have multiple policies. It allows different parts of the application to handle the same exception type in different ways. For example, it can be a policy at the top layer of the exception handling architecture, which specifies the number of customized
Data Exception type packaging exception. It can be another policy for the Web user interface layer. It specifies the exceptions that will be recorded, clears any sensitive or unnecessary information, and then displays it to the user.

You can also use the configuration console to rename or delete an exception policy. The application code uses the name to reference the policy. Therefore, if you delete or rename them, make sure that the application references a valid policy name.

Configuration exception type

Each
Can be configured to handle specific exception types. The application passes the exception to be handled and the name of the policy used to handle the exception to the exception handling Application Block. View the application block search policy as follows:
No. It has been configured to handle exceptions of that type. If it finds a match, the Application Block executes a series of exception handling programs. The Application Block tries to match the exception type in the configuration file as much as possible.
Multiple exception types. If no match is found, the application block searches for the base class of the exception type.

In this method, an application can be configured for a specific exception type (for example, it can be packaged or replaced with a custom application exception type ).System. securityexceptionException type), but it can have different activities for more common exception types (for example, it can recordSystem. ExceptionException logs ). Each exception type can be configured as the action that the Application Block for the exception type will execute after the exception handler chain runs.

Understanding Exception Handling Procedures

You can use the configuration console to configure a handler that must run for each exception type (for example, a handler that Records log information, wraps an exception, or replaces an exception ). You can also configure multiple handlers for each exception type. They run in the order listed in the configuration file.

In
Each exception handler in the chain receives the current exception. For the first handler, this is the original exception. This is an exception that the application passes to the Application Block. Then, any handler in the chain can repair
Change an exception (for example, wrap or replace it with another exception ). The later handler receives exceptions returned by the previous handler. If the specified exception type is configured after the last handler is run
If an exception is thrown, the exception returned from the final handler is thrown. After an exception handling policy is defined for an application, you can modify the application code to apply the policy at an appropriate location. For more information, see send
Exception to Exception Handling Application Block.

3.3-send an exception to the exception handling Application Block

The interaction between application code and Exception Handling application blocks occurs when an application captures an exception and sends it to the Application Block for processing. Application developers do not need to know how the exception will be handled, because they only need to specify the name of the relevant exception policy.

The following code shows how to passDataaccessexceptionType exception to the exception handling Application Block. In this example, a policy named data access policy is applied. Code checkHandleexceptionThe value returned by the method isTrueOrFalse. If the value isTrue, The original exception will be thrown again. All other exception types are propagated back to the call code.

C #
 
Try
{
// Run code.
}
Catch (dataaccessexception ex)
{
Bool rethrow = exceptionpolicy. handleexception (ex, "Data Access Policy ");
If (rethrow)
{
Throw;
}
}

Visual Basic

Try
'Run code.
Catch ex as dataaccessexception
Dim rethrow as Boolean = exceptionpolicy. handleexception (ex, "Data Access Policy ")
If (rethrow) then
Throw
End if

3.4-handle and throw exceptions

When an exception occurs, it is passed up the stack, and each capture block may process it. It is important to capture the order of statements. Place the capture block with the target exception before the common capture block. Otherwise, the compiler may report
An error is reported. The Common Language Runtime (CLR) determines the correct capture block by specifying the exception type and the exception type name in the capture block. If no specific capture block exists
The exception will be handled.

Debugging and Exception Propagation

CLR captures exceptions that are not captured by captured blocks (these exceptions are considered to be unhandled ). When you use the Visual Studio debugger to debug an application, the debugger stops execution when an unhandled exception occurs in the trace stack. This allows you to check local variables and navigate the entire running stack.

Note: : Avoid writing capture blocks that do not do anything except re-throwing the original exception. When the capture block throws an exception again, some debugging information before it is re-thrown in the call stack will be lost. Example
For example, use a mini dump file to debug an application. The file contains a subset of information in a disaster dump file, or if a debugger is attached to a process after an exception is handled, you cannot query local variables.
Stack elements, which are placed in the call stack before the re-throw occurs. The exception is caught only when other activities are required, or the original exception is thrown again as a replacement.

To avoid exceptions that are not handled by capture blocks, write exception-specific capture blocks. If you are using Visual Basic or hosting C ++ for development, you can also use user filtering exceptions.

Handle specific exceptions

Try to catch as many blocks as possible by matching specific exception types. It is recommended that a common capture block rethrow an exception type that is not processed by the capture block. This method achieves the goal of capturing the block clean, and other exception types of the call stack under the debugger are still available.

The following code demonstrates how to handleDataaccessexceptionType exception. In the example, this exception causes the policy named data access policy to be applied.

C #
 
Try
{
// Run code.
}
Catch (dataaccessexception ex)
{
Bool rethrow = exceptionpolicy. handleexception (ex, "Data Access Policy ");
If (rethrow)
{
Throw;
}
}

Visual Basic

 
Try
'Run code.
Catch ex as dataaccessexception
Dim rethrow as Boolean = exceptionpolicy. handleexception (ex, "Data Access Policy ")
If (rethrow) then
Throw
End if

User filtering error

Visual Basic and managed C ++ support user filtering exceptions. The user-filtered exception handler captures and processes exceptions based on information other than the exception type. Additional information allows you to create more precise capture blocks than only exception-type capturing blocks.

Use of the exception handling program filtered by Visual Basic usersCatchStatement andWhenKeyword. Additional information is included inWhenClause, which means that if the clause isTrueThe capture block only handles specific exceptions designed for use. InWhenClause isFalseWill not enter the capture block. This means that the exception will not be caught and the call stack is forbidden when the debugger is used.

This technique is useful when a single exception object corresponds to multiple errors. In this case, the exception Object usually has an attribute that contains the specific Error Code related to the error. You can use the error code attribute in the expression to select onlyCatchSpecial errors to be processed in the statement.

The following visual basic example showsCatch/whenStatement.

Visual Basic
 
Try
'Execute code.
Catch ex as sqlexception when ex. Number = 1204
Dim rethrow as Boolean = exceptionpolicy. handleexception (ex, "Data Access Policy ")
If (rethrow) then
Throw
End if

End try

For details about how to use user filter exceptions in hosted C ++, see using user-filtered exceptions.

For more suggestions on Exception Handling, see best practices for exception handling.

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.