A preliminary study on -12:WCF client exception handling in WCF

Source: Internet
Author: User

Objective:

    • An exception occurs in the client application when we open the WCF Base client channel, either by explicitly opening it or by invoking the operation automatically, by using a client or channel object to invoke the operation, or by closing the underlying client channel. While we know that WCF is a network-based communication service, error exceptions are also based on message passing, and a class faultexception for error message handling is provided in WCF. Next, let's look at how to use it to handle exceptions on the client.

WCF Exception Type:

    • Unexpected exceptions: Unexpected exceptions include catastrophic failures (such as outofmemoryexception) and programming errors (such as ArgumentNullException or InvalidOperationException). There is usually no effective way to handle unexpected errors, so you should not typically catch these exceptions when you invoke a WCF client communication method.
    • Expected exception: Expected exception includes TimeoutException, Communicationexception, and any derived classes of communicationexception. These exceptions indicate a problem in the communication process that can be handled safely by aborting the WCF client and reporting a communication failure. Because external factors can cause these errors in any application, the correct application must catch these exceptions and recover when an exception occurs.

WCF Client Exception Handling instances:

    • The engineering structure is as follows:

  

    • Engineering Structure Description:
    1. Service: Class Library program. Define and implement a service contract that includes add () and divide (), which are addition and division operations.

The ICalculator.cs code is as follows:

  
usingSystem.ServiceModel;usingSystem.Collections.Generic;usingSystem.Runtime.Serialization;namespaceservice{[ServiceContract] Public InterfaceICalculator {[OperationContract]intADD (intValue1,intvalue2); [OperationContract]intDivide (intValue1,intvalue2); }}
View Code

The Calculator.cs code is as follows:

  
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.ServiceModel;namespaceservice{ Public classCalculator:icalculator { Public intADD (intValue1,intvalue2) {            returnValue1 +value2; }         Public intDivide (intValue1,intvalue2) {            Try            {                returnValue1/value2; }            Catch(dividebyzeroexception) {Throw NewFaultException ("the divisor cannot be 0"); }        }    }}
View Code

2. Host: Console Application. To host the service, add a reference to the service assembly, and implement the following code to host the service.

The code for Program.cs is as follows:

  
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingService;usingSystem.ServiceModel;namespacehost{classProgram {Static voidMain (string[] args) {            using(ServiceHost host =NewServiceHost (typeof(Calculator))) {host.} Opened+=Delegate{Console.WriteLine ("Service has been started, press any key to terminate! ");                }; Host.                Open ();            Console.read (); }        }    }}
View Code

The code for App. Config is as follows:

  
<?xml version="1.0"?><configuration> <system.serviceModel> <services> <service name="Service.calculator"behaviorconfiguration="Mexbehavior"> "http://localhost:1234/Calculator/"/> </baseAddresses> ""binding="Wshttpbinding"contract="Service.icalculator"/> <endpoint address="Mex"binding="mexhttpbinding"contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="Mexbehavior"> <servicemetadata httpgetenabled="true"/> <servicedebug includeexceptiondetailinfaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.servi Cemodel></configuration>
View Code

3. Client: Console Application. After the host hosting service is started, the client program adds a reference to the service address http://localhost:1234/Calculator/, sets the namespace to Calculatorserviceref,

Then we can invoke the service. The Program.cs code for the client is as follows:

  

First, we commented out 2, 3 of the code, only to verify the result of the service exception, we set the divisor of the divide to 0, we should capture the exception information thrown by the server. The results of the operation are as follows:

  

Then we put 1, 3 annotations, only the exception that verifies the communication timeout is thrown. We set the operation time after the channel connection to a very small value, then the service side of the operation must be too late to deal with, will throw a surplus

The exception information at the time. The results of the operation are as follows:

  

Finally, we will 1, 2 comments, only verify the communication error exception information, we after the client executes add (), the service terminates, that is, the service terminates the connection will throw a communication error exception information, the result of the operation is as follows:

  

Summarize:

    • With the example, we can see that the client program successfully captured TimeoutException and Communicationexception and custom exception information
    • If an expected exception occurs, the client may continue to use it, or it may not be able to continue. To determine whether the client is still available, check to see if the state property is communicationstate.opened.

If this property is still open, the client can still use it. Otherwise, the client should be aborted and all references to it should be released. The specific reference code is as follows:

if (proxy.) state = = communicationstate.opened) {    Console.WriteLine ("Communicationstate is opened "); }

A preliminary study on -12:WCF client exception handling in WCF

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.