Use ierrorhandle to handle exceptions on the WCF Server

Source: Internet
Author: User

Overview:

In actual project development, we often handle various exceptions.CodeAre constantly filled with try {} catch {} finally {} statement blocks, which are sometimes indispensable, because no one can ensure that the code written by themselves runs normally, the external environment creates the possibility of exceptions, but I often think that the block of statements that capture exceptions often gets the original clear business logic. Of course, the purpose of this article is not to say that exception capture can be completely avoided, but less WCF can free us from exception handling.

 

1,First, let's take a look at the practice of the conventional service implementation class when handling exceptions. Below is a general exception with a division of 0.

General Exception capture

    Public     String  Div ( Int  X,  Int  Y)
{
Int Result = 0 ;
Try
{
Result
= X / Y;
}
Catch (Dividebyzeroexception ex)
{
Throw Ex;
}
Return String . Format ( " {0} " , Result );
}


2,Let's take a look at the code after the ierrorhandler interface is applied to handle exceptions.

   code highlighting produced by actipro codehighlighter (freeware) 
http://www.CodeHighlighter.com/
--> Public string Div ( int X, int Y)
{< br>
return string . format ( " {0} " , x / Y );
}

Do you have a good feeling? If not, think about exception handling in the 1000 methods. This is howProgramThrow an exception and capture it by yourself.

 

3. How to implement it?

3.1,To achieve the above results, we need to customize a class and implement the ierrorhandler interface. The code is quite simple, as shown below:

  Public     Class  Faulterrorhandler: ierrorhandler
{
# Region Ierrorhandler Member
Public Bool Handleerror (Exception error)
{
// To do can be used for logging.
Console. writeline ( " Message: {0}, stacktrace: {1} " , Error. Message, error. stacktrace );
Return True ;
}
Public Void Providefault (Exception error, messageversion version, Ref Message fault)
{
Faultexception fe
= New Faultexception (error. Message, faultcode. createreceiverfaultcode (error. Source, error. stacktrace ));
Messagefault
= Fe. createmessagefault ();
Fault
= Message. createmessage (version, messagefault, " Http://www.microsoft.com/ " );
}
# Endregion
}

There are only a dozen lines of code, which is equivalent to the previous log file code.

 

3.2,For reusability, we hope that all services can use the above Code, so we must create a service configuration class that can be registered in the configuration file, it is also very simple, as follows:

  Public     Sealed    Class  Serviceerrorbehavior: behaviorextensionelement, iservicebehavior
{
Public Void Validate (servicedescription description, servicehostbase ){ Return ;}
Public Void Addbindingparameters (servicedescription description, servicehostbase, system. Collections. objectmodel. Collection < Serviceendpoint > Endpoints, bindingparametercollection parameters ){ Return ;}
Public Void Applydispatchbehavior (servicedescription description, servicehostbase)
{
Ierrorhandler errorhandler
= New Faulterrorhandler ();
// Exception Handling is omitted here.
Foreach (Channeldispatcherbase In Servicehostbase. channeldispatchers)
{
Channeldispatcher
= Channeldispatcherbase As Channeldispatcher;
Channeldispatcher. errorhandlers. Add (errorhandler );
}
}
Public Override Type behaviortype { Get { Return Typeof (Serviceerrorbehavior );}}
Protected Override Object Createbehavior (){ Return New Serviceerrorbehavior ();}
}

The above code is just a dozen lines, which is quite simple. To register a configuration in the configuration file, I implemented the behaviorextensionelement class and overwritten the behaviortype attribute and createbehavior method of behaviorextensionelement, the service host automatically obtains the behaviortype and creates an extension configuration node through the createbehavior method. The iservicebehavior interface is implemented to add a custom exception handler in the service distribution channel. In this way, when a service exception occurs, the WCF Service can find the corresponding errorhandler Handler through this configuration node, and automatically call.

 

4,Register the custom Extension Configuration section in the configuration file. All we need to do is copy the following lines of code to the app. config, and put it in system. under the servicemodel node.

  < Extensions  >  
< Behaviorextensions >
< Add Name = "Enforcegreetingfaults" Type = "Common. serviceerrorbehavior, common, version = 1.0.0.0, culture = neutral, publickeytoken = NULL" />
</ Behaviorextensions >
</ Extensions >


4.1,Then, add the above extension configuration to the service configuration, that is, add enforcegreetingfaults here. The green part is the name of the above extension node:

Register extended configurations

  < Servicebehaviors  >  
< Behavior Name = "Wcfservice. service1behavior" >
< Servicemetadata Httpgetenabled = "False" />
< Servicedebug Includeexceptiondetailinfaults = "True" />
< Enforcegreetingfaults />
</ Behavior >
</ Servicebehaviors >


5,Finally, the client will continue to call the service.

 

6,Special note: when creating a service extension node (behaviorextensions), you need to carefully checkType = "common. serviceerrorbehavior, common, version = 1.0.0.0, culture = neutral, publickeytoken = NULL"Remember to include a space after ",". Remember to include one character. There must be no more or less. Otherwise, the service host fails to be registered.

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.