WCF distributed development step for Win (15): Error contract (FAULTCONTRACT) and exception handling (Exceptionhandle)

Source: Internet
Author: User
Tags reflector

Today learn the WCF distributed development step for the 15 section of the win series: Error Contracts (FAULTCONTRACT) and exception handling (Exceptionhandle). This section is an important knowledge point for WCF distributed development, and should be understood in both learning and projects. The knowledge of WCF exception handling has also been discussed with a number of learning enthusiasts before. Here is a systematic arrangement, a total of reference for everyone. At the same time, the "WCF distributed development step-by-step to win" series of articles to improve and complement.
This section mainly involves the knowledge point is: "1". NET exception Handling "2" WCF Exception handling "3" Error Contract "4" WCF Exception Handling Extension "5" Sample code analysis, and finally the "6" Summary section.
First, let's recall. NET an important concept of exception handling Exceptionhandle. Exception handling in the Java platform also has its own mechanism, this is not a WCF-specific concept, also to understand the WCF exception handling, we need to first understand its predecessor. NET exception handling related concepts.
"1". NET exception handling:
Managed exceptions in the. NET Framework are implemented with the WIN32 structured exception handling mechanism. The common language runtime provides a model for notifying programs of errors in a unified manner, which provides a great help in designing fault-tolerant software. All. NET framework operations indicate that an error occurred by throwing an exception. Traditionally, the error-handling model of a language relies on a unique approach to language detection errors and lookup error handlers, or relies on the error-handling mechanisms provided by the operating system. Exception handling implemented by the runtime has the following characteristics:
Handle exceptions without regard to the language that generated the exception or the language that handled the exception.
Exception handling does not require any specific language syntax, but rather allows each language to define its own syntax.
Allows exceptions to be thrown across processes and even across machine boundaries.
Exceptions have several advantages over other methods of error notification, such as return codes. There is no longer a case of error without being noticed. Invalid values do not continue to propagate in the system. You do not have to check the return code. You can easily add exception handling code to increase the reliability of your program. Finally, the runtime's exception handling is faster than Windows-based C + + error handling.
Because execution threads routinely traverse managed and unmanaged blocks of code, the runtime can raise or catch exceptions in managed code or unmanaged code. Unmanaged code can contain both C + +-style SEH exceptions and COM-based HRESULT.
Exception handling usingTryCatchAndfinallyKeyword to try some actions to handle the failure situation, although these actions may fail, but if you are sure you need to do this and you want to clean up the resources afterwards, you can try this. Exceptions can be generated by the common language runtime (CLR), the. NET Framework, or any third-party libraries or application code. Exceptions are used throw   keywords created. (MSDN)
"2" WCF exception handling:
   Now let's look at the exception handling mechanism for WCF. We introduced the above. NET exception handling mechanism. WCF is also part of the. NET Framework, and many of them are handled essentially the same way. However, because of its cross-service platform target requirements, WCF does not support the traditional exception handling methods. The traditional way. NET throws an unhandled exception that immediately terminates the main process, while WCF does not.
"2.1" WCF Error Type:
   in the process of developing WCF distributed applications, our clients often encounter three common errors.
(1): Communication error, possibly and network, channel and other related anomalies, the client is communication Exception;
(2): The state of the proxy and channel, the agent is closed, or the channel fault, and so on, this is more common. General channel idle time too long, the channel will appear this state error problem. In general, we can judge by the state of the agent. This error can also be caused by a security validation failure.
(3): Service invocation error, exception thrown during service invocation, this service internal exception is serialized to the client and captured by the client.
    The third is the type of detail we have in this sectionto.
"2.2" FaultException:
   The key problem here is that The exception information thrown by a WCF service is often based on the internal exception information of. NET, which cannot be serialized, nor can it implement shared error information on the client and the server.
    Therefore, if the exception is handled in a traditional way in a WCF service, the client cannot capture and handle the exception that the service throws because the exception message cannot be serialized. To solve this problem, WCF provides the faultexception. This is an industry-standard SOAP Exception class, and WCF handles unrecognized exceptions as a uniform FaultException exception object, so you can pass the error message to the client and the client can capture FaultException or exception. You can view the definition of this class through. NET reflector, and some of the code for FaultException is as follows:

[Serializable, Knowntype (typeof (Faultreasondata[])), Knowntype (typeof (Faultcodedata)), Knowntype (typeof ( Faultcodedata[]), Knowntype (typeof (Faultreasondata))]
public class Faultexception:communicationexception
{
Fields
private string action;
Private FaultCode Code;
Private Messagefault fault;
Internal const string Namespace = "http://schemas.xmlsoap.org/Microsoft/WindowsCommunicationFoundation/2005/08/Faults/";
Private Faultreason reason;

Methods
public FaultException ();
}

We can notice that the faultexception has a serialized tag. Declared the serializable.
Another important generic definition for faultexception is faultexception<t>, where we can use any system type or custom type to pass an error message, and T represents the error detail to pass. This class can also use the reflector to view the code:

Code

"3" Error contract Faultcontract:
When it comes to WCF exception handling, here's an important concept: Error contracts (faultcontract).
The faultexception of WCF has been introduced earlier, so why do we have to faultcontract.
By default, WCF passes the exception thrown by the service to the client in the FaultException type.
However, WCF stipulates that any exceptions that are shared by clients and services must belong to the attributes of the service behavior. That is, we must define the service contract for the feature's service operation to provide the error type. WCF specifically provides the Faultcontract attribute for exception handling, which can be applied to service operations to indicate the type of exception that an operation might throw. The code is as follows:

[AttributeUsage (AttributeTargets.Method, Allowmultiple=true, Inherited=false)]
public sealed class Faultcontractattribute:attribute
{
Fields
private string action;
private bool Hasprotectionlevel;
private string name;
.
}

The error contract faultcontract is actually one of the WCF4 contracts (Service contract,datacontract,messagecontract,faultcontract). Declares a service operation contract method as faultcontract and specifies the type parameter of the response, which is consistent with the type of faultexception<t>.
"4" WCF Exception Handling extensions:
WCF allows developers to customize the process of exception reporting and exception passing. But to implement the System.ServiceModel.Dispatcher.IErrorHandler interface:
Ierrorhandler is defined as follows:

public interface Ierrorhandler
{
Methods
BOOL HandleError (Exception error);
void Providefault (Exception error, messageversion version, ref Message fault);
}

The exception that is thrown by the server will then call the Providefault () method before returning to the client. Providefault does not consider the type of exception.
In addition providefault an important function, abnormally elevated (Exception Promotion). It can promote non-faultcontract exceptions to faultcontract<t> exceptions, such as promoting OverflowException exceptions to faultexceptino< OverflowException > Exceptions. Instead of the HandleError () method, we can re-implement the code, such as log logs.
In addition, if you want to install your own custom ierrorhandle, you need to add it to the corresponding distributor.
We implement the installation error handling extension in the service class implementation System.ServiceModel.Description.IServiceBehavior Interface ApplyDispatchBehavior () method. The main methods of IServiceBehavior are applydispatchbehavior:

public interface IServiceBehavior
{
Methods
void Addbindingparameters (ServiceDescription servicedescription, ServiceHostBase servicehostbase, Collection< serviceendpoint> endpoints, bindingparametercollection bindingparameters);
void ApplyDispatchBehavior (ServiceDescription servicedescription, ServiceHostBase servicehostbase);
void Validate (ServiceDescription servicedescription, ServiceHostBase servicehostbase);
}

"5" Sample Code Analysis:
Here's a simple example code for this section of the article.
"5.1" Service side:
Here we define two service operation methods, mainly to test the WCF exception handling, SayHello and Saygoodbye. The parameter is a string name, and a OverflowException memory overflow exception is thrown when the length is greater than 10, and then we wrap it through faultexception and pass it to the client. Here we also apply the Faultcontract feature to the Operation contract. The definition code is as follows:

1. Service Contract
[ServiceContract (Namespace = "http://www.cnblogs.com/frank_xl/")]
public interface Iwcfservice
{
Operation contract
[OperationContract]
[Faultcontract (typeof (OverflowException))]//annotation, the WCF client can differentiate the error contract, otherwise it will be thrown as a communication exception
String SayHello (string name);
Operation contract
[OperationContract]
[Faultcontract (typeof (OverflowException))]
String Saygoodbye (string name);
}
2. Service class, inherit interface. Implementing the operations defined by the service contract
public class Wcfservice:iwcfservice
{
Ways to implement an interface definition
public string SayHello (string name)
{
if (name. Length < 10)
{
Console.foregroundcolor = Consolecolor.green;
Console.WriteLine ("Hello! {0}, ", name);
Return "hello!" + name;
}
Else
{//generic class faultexception, can contain different exceptions, can be serialized. SOAP-based error messages
OverflowException oe = new OverflowException ();
throw new faultexception<overflowexception> (OE, "name Length is more than 10");
}
}
Ways to implement an interface definition
public string Saygoodbye (string name)
{
if (name. Length < 10)
{
Console.foregroundcolor = Consolecolor.green;
Console.WriteLine ("Goodbye! {0}, ", name);
Return "hello!" + name;
}
Else
{
OverflowException oe = new OverflowException ();
throw new faultexception<overflowexception> (OE, "name Length is more than 10");
}
}
}

"5.2" Host:
Here the host is still the console program, self-hosted WCF service. Each time the call information is printed. Relatively simple, the code is as follows:

static void Main (string[] args)
{
Reflection mode to create a service instance,
Using-mode life instances, which release unmanaged resources at the end of the object life cycle
using (ServiceHost host = new ServiceHost (typeof (Wcfservice.wcfservice)))
{
Determine if and open the connection, open the listening port if it is not already open
if (host. State = communicationstate.opening)
Host. Open ();
Show running status
Console.foregroundcolor = Consolecolor.yellow;
Console.WriteLine ("Host is runing! and state is {0} ", host. State);
Console.foregroundcolor = consolecolor.red;
Print endpoint Information
foreach (ServiceEndpoint se in host. description.endpoints)
{
Console.WriteLine ("Host is listening at {0}", se. Address.Uri.ToString ());

}
Wait for input to stop service
Console.read ();
}
}

"5.3" Client:
The client passes two parameters respectively, the first normal call, the second parameter length is greater than 10, causes the service side exception, then runs out to the client, the client handles the exception according to the defined faultexception<t>. The code is as follows:

Wshttpbinding_iwcfservice
Test.wcfserviceclient wcfserviceproxyhttp = new Test.wcfserviceclient ("Wshttpbinding_iwcfservice");
Calling the SayHello service via proxy
Try
{
Console.WriteLine (Wcfserviceproxyhttp.sayhello ("Frank Xu"));
Console.WriteLine (Wcfserviceproxyhttp.sayhello ("Frank Xu Lei Wshttpbinding"));
}
catch (faultexception<overflowexception> OE)
{
Console.WriteLine (OE. Message);
}
catch (communicationexception CE)
{
Console.WriteLine (CE. Message);
}
Finally
{
Wcfserviceproxyhttp.close ();
}

For Debug
Console.WriteLine ("Press any key to exit");
Console.read ();

Here to run the program, the test results are as follows:

"6" Summary:
The above is the entire contents of WCF exception handling. A few points we should note:
(1) Even if we do not add the Faultcontract attribute, or throw a non-faultexception exception, the client can also get an exception message, which causes the channel error.
(2) In addition, we can set the includeexceptiondetailinfaults of the service to True (by default, false) by adding the ServiceBehavior feature. The client can also catch thrown non-faultexception exception information, but the exception still causes a channel error.
(3) The effect of exceptions on WCF service instances is related to the type of activation of the service. Typically monotonic Percall and session patterns, WCF service exceptions cause the service to release the service instance, and the single singleton mode does not, and the WCF service continues to run.
(4) When publishing services and deploying services, we should avoid setting the includeexceptiondetailinfaults of the service to true. This brings performance issues.
Finally, the reference code for this article is given:/files/frank_xl/wcfserviceexceptionhandlefrankxulei.rar
Reference article:
1.http://msdn.microsoft.com/zh-cn/library/ms173160.aspx
2.http://msdn.microsoft.com/zh-cn/library/ms954830.aspx
3.WCF Services Programming

WCF distributed development step for Win (15): Error contract (FAULTCONTRACT) and exception handling (Exceptionhandle)

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.