Exception Management Architecture Guide

xiaoxiao2021-03-06  67

Exception Management Architecture Guide, MANAGEMENT ARCHITECTURE

Abnormal Management Framework Guide

Abnormal management

To architecture a good structure, high maintenance, elastic application systems must adopt appropriate exception management strategies. The system's exception management must contain the following functions:

l detect abnormalities

l Record an abnormal log, send information

l Generate an abnormal event to enable external systems to monitor and make judgments.

To architecture a good structure, high maintenance, elastic application systems must adopt appropriate exception management strategies. The system's exception management must contain the following features

1.1 abnormal hierarchy

Exceptions are typically triggered by applications (user programs, etc.) or runtime (public language runtime, and application running libraries). Exception is a base class for all exception types. When an exception occurs, the system or currently executable application reports an exception by trigger an exception containing information about the error. After the abnormality occurs, it will be processed by the application or the default exception handler. Several exception classes are inherited directly from Exception class, including two main types of exception classes:

ApplicationException

User-defined application exception type base class. ApplicationException inherits Exception, but does not provide extension, you must develop the derived class of ApplicationException to implement custom exceptions.

2. SYSTEMEXCEPTION

The base class of the predefined public language running library exception class.

These two exception classes constitute almost all applications and running abnormalities.

1.1 abnormal processing process

The abnormal processing process is mainly composed of "analysis exception" and "processing exception". The method (process) in the application system must be in accordance with the following procedure to ensure that the current method (process) context is included in the abnormality information processed. > Note: An exception is generated in the method (process), and enter the "abnormal detection" code block. The details of the abnormalities are discussed in the "Exploratory" and "Abnormal Transfer" code blocks. When an exception is propagated to the boundary of the application system (the exception information is required to feed back the user), the exception management enters an exception handling phase, see the figure below:> Note: In order to maintain an abnormal information, the Nofice and the user experience / User Experience, exception handling enters information collection, logging, and notice abnormal processes. Abnormal detection

The public language runtime of .NET provides an exception handling model that is based on an exception representation in the form of an object, and the program code and exception processing code are divided into the TRY block and the CATCH block. You can have one or more CATCH blocks, each block is designed to process a particular type of exception, or design a block to capture more specific than other blocks.

try {// Some code that could throw an exception.} catch (SomeException exc) {// Code to react to the occurrence // of the exception} finally {// Code that gets run always, whether or not // an exception Was thrown. this is usually // clean up code That Should Be Executed // Regardless of WHETHER AN Exception Has // Been Thrown.}

If you want to handle an exception that occurs during a code block during execution, you must first place the code block in the TRY block. (The code in the try statement is the TRY block) and will process an exception that caused by the TRY block in the catch statement, called a Catch block. Zero or more CATCH blocks are associated with a TRY block, each CatCH block contains a type filter that determines an exception type that can be processed. Regardless of an exception or not, the application will enter the Finally block, usually to perform some Clean UP code. Note: When an exception occurs in the TRY block, the system searches them in the order of the application code associated with the CATCH block until it is positioned to the Catch block processed by the abnormality. If the type filter of a CATCH block specifies the exception type T or any fault is derived from an exception type T, the Catch block processes the T type and its derived type. The system stops searching after finding the first CATCH block that handles the exception. Therefore, the CATCH block that handles a type of exception in the application code must be specified before processing the CATCH block of its base type, so the Catch block of System.Exception is usually processed. If all CATCH blocks associated with the TRY block do not process the exception, and the current TRY block is nestled in other TRY blocks, the CATCH block associated with the previous TRY block is searched. If there is still no Catch block for this anomaly, the exception edge tuning stack is passed upward, search for a stack frame (the main method of the current method) to find the Catch block that handles the exception and looks until it Abnormally gets more frames in the processing or call stack. If the Catch block that is not found in the top of the calling stack, the exception is processed by the default exception handler, and then the application terminates. When performing the following specific operations, the application needs to capture exceptions: l Collect information and log the log.

l Add some relevant information for the current exception

l Execute a Clean UP code

l Try to restore an exception (resolve) 1.1 Appropriate use of exceptions

Errors that appear except for application ideas should use an exception, and an error that appears within the application idea is generally not necessary. "

For example, a user logs in to the application system because the wrong account or password cannot be logged in. "Login Fail" has been in the system's expectations, in this case, there is no need to use exception management. But an unpredictable error is to capture an exception, such as user login failure is caused by database connection failure.

In addition, throwing an abnormal resource overhead is greater than returning a simple result to a function (process) caller and excessive use of exceptions generates a code that is difficult to read and manage, so do not use abnormal management for controlled execution flow.

1.2 Capture of the runtime

In a particular new environment, the exception thrown by the application will intercept during runtime, and these exceptions will involve stack resources. For example, calling the Objects in an ArrayList to use Object's COMPARETO method, which throws the System.invalidOperationException Exception, and may generate system.reflection.targetinvocationException when calling the "reflection" method. These exceptions can be set to Innerexception (internal abnormal properties) throws at runtime. These exceptions must be handled so that they have the smallest impact on the application system. For details, please click on the link below:

l Base Exception Hierarchy

l Common Exception Classes

l System.exception Class

2. Abnormal dissemination

There are three ways to spread abnormalities:

l let abnormal automatic communication

The code segment can deliberately ignore the exception. When an exception occurs, the code segment stops execution, enter the stack until the stack address is found with the current exception.

l Capture the abnormality

Capture an exception in the code segment, then execute the Clean Up or some necessary process code in the current code segment. If you don't solve an exception, you will throw it to the caller.

l Capture, packaging, throw a packaged exception

Abnormality spread from the stack is often lacking type correlation. After the packaged abnormality is returned to the caller, it will be more readable and more dependent. The following figure explains the process of exception capture, packaging, and thrown. With this way, the application can capture exceptions and then perform Clean Up or some necessary process code. If an abnormality cannot be resolved, the exception is re-encapsulated and the function (process) caller is thrown. Setting the Innerexception property allows the exception source to "internal exception" and "external exception" with context-dependent. Innerexception property settings can be performed when constructed. > When the abnormality spreads, the CATCH code segment can only capture "external exception", and the internal exception can be accessed through the Innerexception property. The following code describes the implementation process:

Try {// Some Code That Could throw an exception.

Catch (TypeaException E) {// code to do any processing needed. // Rethrow the Exception throw;}

catch (TypeBException e) {// Code to do any processing needed // Wrap the current exception in a more relevant // outer exception and rethrow the new exception throw (new TypeCException (strMessage, e));..}

Finally {// code That Gets Executed regardless of WHETHER // AN Exception Was thrown.}

Note: The first CATCH code segment captures TypeaException exception, performs some necessary process code, and then throws this exception to the caller. The second CATCH code segment packages TypeBexception into a context-dependent new exception TypeceXception, and throws the caller as an external exception. In this example, the code block only cares about the exception TypeaException and TypeBexception, and other exceptions will automatically spread up.

The following is the advantages and disadvantages of three propagation pathways:

way for spreading

Whether it is allowed to process

Whether to add correlation

Let the abnormality are automatically spread

no

no

Capture the abnormality

Yes

no

Capture, packaging, throw out the packaged exception

Yes

Yes

1.1 When is internal abnormalities

An abnormally initially propagated only the accurate reason for exception, when an exception throws to the caller, it has a small amount of context correlation, which requires this line of exception packaging.

For example: Call the LoadUserInfo method The local file of the server needs to read the server. If the file does not exist, the code segment will throw the FileNotFoundException exception to the caller. However, in the LogonUser method, the "file unrecognizable" appears, it is obviously difficult to read, if FileNotFoundException is packaged into a custom exception, FailedToloaduSerInfoException, add external information and context-dependent in FailedToloadUserInfoException, which will more comply with the Logonuser method. 2. Customized exception

.NET Framework is an exception system that uses an exception type. The application establishes an exception system from the hierarchy of ApplicationException, as shown below:> Hierarchical custom exception system Bring the following benefits to the application:

l Easy to develop, because you can expand your properties through inheritance

l When the system is deployed, it is still possible to expand new custom exceptions by inheritance. There is no need to change the abnormal processing code that has been written, because the expansion exception is derived from the base class anomaly, the processing of the base abnormality is the abnormality that is derived.

1.1 Design hierarchical structure

The .NET Framework uses an extended, hierarchical exception system, if appropriate exception has been defined, an exception provided by .NET Framework. Most of the organization's hierarchy abnormal system needs to smoothes, group, and expand new properties and functions.

Whether to establish a custom abnormality in the application system, you can refer to the following questions:

l Is there an abnormality in current conditions?

An exception appearing under the .NET Framework does not have to be customized.

l Do you need a separate processing?

A new anomaly class should be recommended such that the code block can capture the exception and make it clearly processed. This eliminates the handle of some non-special exceptions, and decides to perform an action by logic judgment.

l Do you want to perform a special handling or add information in an abnormality?

You can create a new "Apply Level Exception" class to add information and functions to an exception based on special needs.

Usually put an exception hierarchy of an application system in a program set, so that the application can add a reference and facilitate the management and deployment of the sub-definition.

1.2 Creating a custom anomalous class

Customization has a good name habit. At the end of Exception, and to express the implementation of the following three constructors.

using System; public class YourBaseApplicationException: ApplicationException {// Default constructor public YourBaseApplicationException () {} // Constructor accepting a single string message public YourBaseApplicationException (string message): base (message) {} // Constructor accepting a string message and an / / inner exception which will be wrapped by this // custom exception class public YourBaseApplicationException (string message, exception inner): base (message, inner) {} 1.2.1 build custom exception derived from ApplicationException all custom exceptions inherited ApplicationException. Information is generally added to the custom abnormality to add "exceptional time", "server name", "run account" and other information. Compress exceptions into an abnormality of a base class, improve the availability of custom abnormalities by inheritance. 1.2.2 Remote Access Custom Abnormal Anomaly class implements the iSerializable interface, through serialization, exceptions will be accessed by the remote service through the system boundary. To achieve remote access, you must add [Serializable] to the class definition, and the following constructor is implemented:

protected YourBaseApplicationException (SerializationInfo info, StreamingContext context): base (info, context) {} if custom exception added some field properties, it is necessary to override GetObjectData method, and the corresponding field is loaded into the SerializationInfo properties, as follows:

[Serializable] public class ExampleException: ApplicationException {public ExampleException (): base () {} public ExampleException (string message): base (message) {} public ExampleException (string message, Exception inner): base (message, inner) {} Protected ExampleException (SerializationInfo Info, StreamingContext Context): Base (Info, Context) {m_StrMachinename = Info.getstring ("m_strmachinename");}

public override void GetObjectData (SerializationInfo info, StreamingContext context) {info.AddValue ( "m_strMachineName", m_strMachineName, typeof (String)); base.GetObjectData (info, context);}

Private string m_strmachinename = environment.machinename;

Public String MachineName {GET {Return M_STRMACHINENAME;} set {m_strmachinename = value;}}} By custom anomaly class constructor, the corresponding field attribute in an exception passes to the remote server via the SerializationInfo object, obtained by serializationInfo's getValue method information. For details, please click on the link below:

l .NET Framework Developer's Guide: Best Practices for Handling Excetions

l Handling and throwing Exceptions

l Implementing iSerializable

l Serialization Sample

2. Manage unreated exceptions

When an unprocessed exception spreads to the boundaries of the application and the user, the system cannot solve the abnormality. At this time, in order to manage communication with users, information, log log, send advertisement, execute Cleanup and the necessary process code. In most web-based applications, the boundaries of exceptions and end users are controlled by web pages or web services. The following will discuss how the system boundaries manage unprocessed exceptions.

2.1 ASP.NET

ASP.NET provides some specific ways to manage exceptions and set exception information to display to end customers.

2.1.1 Setting Web.config

Set the default redirection page in CustomerrorS, the following is three setup modes:

l on

Unprocessed anomaly redirects the user to a unified default page. Generally used in productization mode.

l off

The user will see an exception prompt information, not a redirect to the unified default page. Generally used for project development models.

l Remoteonly

The exception prompt information will be seen when the user accesses the local server through "localhost", while other users will redirect to a unified default page. Generally used in Debug mode.

In addition to redirecting to the default page, you can set a specific page for some HTTP error code. For example, all 404,500 errors are directed to a particular page. Before .NET, you must implement the above orientation, you must set the Matabase in IIS. ASP.NET focuses all application settings into web.config, and deployment can be implemented via XCOPY.

It must be noted that these settings are only valid (ASPX, ASMX) on the ASP.NET file, such as files that use HTM, ASP, etc. by the user call the application server, and IIS will return to the HTTP error settings on Matabase, not web.config. setting. At this point, you must match the redirect page of Matabase and Web.config.

2.1.2 Using @ Page Directive Web.config will act on the current directory and all subdirectories, set a specific redirection page by overwriting the ErrorPage property in the Page ID. In the following example, if the end user has never processed The exception will jump to the Customerror.aspx page:

<% @ Page ErrorPage = "Customerror.aspx"%> 2.1.3 Processing ASP.NET ASP.NET provides two events to handle exceptions thrown in the code.

l Page_ERROR

This event will be activated when the page level is unable to resolve. At this point, you must include an event handle of page_error or an @ page directive, and the event handle code of page_error is as follows:

Page. Error = New System.EventHandler (Page_ERROR); L Application_ERROR

The code block of the Application_Error event is in Global.asax, which is the application level. This event will be activated when there is an abnormality that cannot be resolved in some special pages. The "Log Record", "Notification", "The necessary processing code" should be designed in the code block of the Application_ERROR event, as follows:

// in global.asax file

Protected Void Application_ERROR (Object Sender, Eventargs E)

{

Exception Exc = Server.getlasterror ();

// Perform logging, Send Any Notifications, ETC.

}

Note: The server.getlasterror method obtains the current unprocessed exception object, the server.clearerror method clears the current unprocessed exception object and stops abnormal propagation. For example, the application's page should contain the server.getlasterror method to access the current unprocessed exception object. If you don't use the Server.clearrror method to clear the exception, then exceptions will be propagated into the Application_ERROR event, if not clear, Jump to the exception jump page set in Web.config. For details, please click on the link below:

l asp.net homepage

l Section

1.1 Web Service

Web services use Simple Object Access Protocol (SOAP) to spread exceptions, and .NET Framework provides the SOAPEXCeption class to handle exceptions. When the CLR receives the SOAP request from the client's error format, the SOAPEXCEPTION is automatically thrown. The exception thrown by the web service method will be unified to be packaged into a soapexception exception, respond to the Client that throws to the web service through the SOAP.

2. Collect information

The application must capture appropriate exception information that is used to clearly describe the abnormal environment. What to do is to convert them into an easy acceptable information, and the role of accepting information includes the following:

l terminal user

Need to get mean, friendly information

l application system developer

Need to learn more about abnormal details, provide assistance to solve problems

l operator

Require information and procedures for solving problems

2.1 Capture appropriate information

All characters have to receive information related to them, allowing them to handle problems properly. Do not throw all the information to the above roles. For example, the end user does not have to know what exception is that the method (process) is abnormal. Similarly, users also hate the "error, please contact the administrator contact" and other prompt information, and the exception information displayed to the user should be friendly and can try to guide the user to correct errors. The following table shows the angle of attention of the role to exception information:

Character

Pay attention

End user

1) give a prompt to the user, tell the request is successful

2) give friendly news, tell what problems

3) Inform how to try corrective errors

Application system developer

1) Expressive time

2) Accurately positioned to abnormal code blocks

3) Explicitly appear anomalies

4) Information, system status, etc. related to exception

operator

1) Abnormal appearance time

2) Accurately positioned to abnormal code blocks

3) Resource name and notification information that needs to be issued

4) Inform whether to solve the problem in some operations or developments in the abnormal type

Applications need to provide rich exception information to ensure that they can be cut to each role, and the exception captured should include the following table information:

data

source

Date and Time of Exception

Datetime.now

Machine Name

Environment.machinename

Exception Source

Exception.Source

Exception Type

Type.Fullname Obtained from Object.gettype

Exception Message

Exception.Message

Exception Stack TRACE

.

Call Stack

Environment.stackTrace-The Complete Call Stack.

Application Domain Name

Appdomain.FriendlyName

AskEMBLY NAME

AskEMBLYNAME.FULLNAME, IN THESTEM.REFLECTION NAMESPACE

AskEMBLY VERSION

Included in the assemblyname.fullname

Thread ID

Appdomain.getCurrentthreadID

Thread User

Thread.currentPrincipal in the system.threading namespace 2.2 Access exception data

Abnormalities have a variety of structures, by capturing exposed attributes, the system gets information such as abnormal reasons. Using reflection (see System.Reflection Name Space), the system easily obtains an abnormal property value, and detailed exception information guides developers to find an abnormal source. For details, please click on the link below:

l Reflecting on Stack Traces

l System.Reflection Namespace

3. Application Meter Instrument Embedding Procedure, providing data in a specific person monitoring application. The application instrument is a good tool for mastering system execution status and evaluation system. Enterprise Instrument Frame (EIF) provides a good flexible approach to handle application events (including exception), and EIF uses Event Sources and Event Sinks to separate the system log from the advertisement release. But when processing anomalies, we often need to propose logging and advertisements.

First publish translation articles, please have a lot of men. Original English article Address: http://msdn.microsoft.com/library/en-us/dnbda/html/exceptddDotNet.asp? Frame = true

转载请注明原文地址:https://www.9cbs.com/read-109325.html

New Post(0)