DCSIMG
WCF Exception Handling with Exception Handling Application Block Integration - Guy Burstein's Blog

Guy Burstein's Blog

Developer Evangelist @ Microsoft

News

Guy Burstein The Bu

Disclaimer
Postings are provided 'As Is' with no warranties and confer no rights.

Guy Burstein LinkedIn Profile

TwitterCounter for @bursteg

Links

Articles

Blogs I Read

WCF Exception Handling with Exception Handling Application Block Integration

WCF Exception Handling with Exception Handling Application Block Integration

This post is one of a post series about WCF Integration in Enterprise Library 3.0. Specifically, this post is the first post I am talking about the integration between Exception Handling Application Block and Windows Communication Foundation (WCF). This post has a brief overview about the Exception Handling Application Block (EAB) and the WCF Fault Handling. Then, this post explains how to use the EAB integration with WCF.

Exception Handling Application Block

If you're familiar with the Exception Handling Application Block, you can skip to the next section. If you're not, stay around. To simply put it, the EAB works with exception handling policies. You configure a exception policy in the configuration file, and add one or more exception handlers to it. For example, the following configuration snippet configures a policy called "Server Policy" that replaces a Security Exceptions with Application Exceptions, and wraps a DB Concurrency Exception with a custom Exception Type.

<exceptionPolicies>

  <add name="Server Policy">

    <exceptionTypes>

      <add name="SecurityException"

           type="System.Security.SecurityException 

           postHandlingAction="ThrowNewException">

        <exceptionHandlers>

          <add name="Replace Handler"

               type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler"

               exceptionMessage="Replaced: User is not authorized to perform the requested action."

               replaceExceptionType="System.ApplicationException, mscorlib" />

        </exceptionHandlers>

      </add>

      <add name="DBConcurrencyException"

           type="System.Data.DBConcurrencyException, System.Data"

           postHandlingAction="ThrowNewException">

        <exceptionHandlers>

          <add name="Wrap Handler"

               type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler"

               exceptionMessage="Wrapped Exception: An error occurred while attempting to access the DB."

               wrapExceptionType="MyApplicationException, MyApplication.Excecptions" />

        </exceptionHandlers>

      </add>

    </exceptionTypes>

  </add>

</exceptionPolicies>

Then, on order to handle an exception when caught, we use the following code:

try

{

    // Do some operation that may cause an exception

}

catch

{

    // Use the EAB to handle the exceptions according to the configuration

    if ( ExceptionPolicy.HandleException(ex, "Server Policy") ) throw;

}

WCF and Exceptions

WCF Exception Handling These is a lot to say about what happens when an exception occurs in a WCF Service Operation. To make a long story short, I'll say that the exception is not thrown back to the client and the channel becomes in Faulted state. The idea behind this design is that you don't want to reveal any information about the error that has occurs because it can contain information you don't want to share. For example, if you expose a Web Service to the Internet for other organizations to consume, you don't want them to know that you cannot insert a new record to table "tblUsers" because a user with name "Guy" already exists.

If you still want to return excecptions back to the client (recommended only during development time), you can add a service behavior: 

<serviceBehaviors>

  <behavior name="Debug">

    <serviceDebug includeExceptionDetailInFaults="true" />

  </behavior>

</serviceBehaviors>

Note that this configuration is used only for unhandeled exceptions. If you are using a FaultContract to specify what type of faults your service might return, this setting will not change a thing about it.

Exception Handling Application Block Integration with WCF

In this post, I will not get into details about how the integration works, and I will focus on the things you should do or configure in order to benefit from this integration.

First, you have to create a Data Contract that will contain the details about the error that has occurred. For example:

[DataContract]

public class ServiceFault

{

    private string message;

    private Guid id;

 

    [DataMember]

    public string MessageText

    {

        get { return message; }

        set { message = value; }

    }

 

    [DataMember]

    public Guid Id

    {

        get { return id; }

        set { id = value; }

    }

}

Second, you have to create a WCF shielding policy in the exception handling policies section in the configuration file, as displayed in this configuration snippet.

<exceptionHandling>

  <exceptionPolicies>

    <add name="WCF Exception Shielding">

      <exceptionTypes>

        <add type="System.InvalidOperationException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="ThrowNewException" name="InvalidOperation">

          <exceptionHandlers>

            <add           type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF.FaultContractExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF"

              name="DefaultFaultContract Handler"

              faultContractType="Bursteg.Samples.WCFIntegration.ServiceContracts.ServiceFault, Bursteg.Samples.WCFIntegration.ServiceContracts">

              <mappings>

                <add name="Id" source="{Guid}"/>

                <add name="MessageText" source="{Message}"/>

              </mappings>

            </add>

          </exceptionHandlers>

        </add>

      </exceptionTypes>

    </add>

  </exceptionPolicies>

</exceptionHandling>

There are few things that you should notice in the above snippet:

1. The default name of the exception handling policy is WCF Exception Shielding. The exception handling app. block will look for this name if you don't tell it otherwise (more details later).

2. Make sure that the PostHandlingAction of the policy is ThrowNewException. This means that the exception with the FaultContract in it will be thrown after the handling is done.

3. The Exception handler called DefaultFaultContract  Handler is an Exception Handler of type FaultContractExceptionHandler (more details on the next post) which converts the handled exception (this time it's System.InvalidOperationException) to the FaultContract specified in the faultContractType attribute.

4. What this handler does in order to convert an exception to the configured fault contact, is simply mapping of properties according to the <mappings> list above. In this case the property MessageText in the ServiceFault class will get the value in the Message property of the exception. Notice that the Id property of the ServiceFault is mapped to the source {Guid}. This means that the Id property will have the Handling Instance Id property of the exceptions that is automatically created by the Exception Handling Application Block.

Third, you have to add the exception shielding into the service contract or the service class. This is done by the [ExceptionShielding] attribute.

[ServiceContract]

[ExceptionShielding]

public interface IOrdersService

{

    ...

}

If you changed the name of the policy that the exception shielding is using from WCF Exception Shielding, or you have many services and each one has its own specific policy, you should pass the name of the policy to this attribute:

[ServiceContract]

[ExceptionShielding("Policy Name")]

public interface IOrdersService

{

    ...

}

As I mentioned earlier, the FaultContractExceptionHandler converts the exception to a Fault Contract. This means that you have to specify the FaultContract to your service contract in order for receiving it in the client side:

[ServiceContract]

[ExceptionShielding]

public interface IOrdersService

{

    [OperationContract]

    [FaultContract(typeof(ServiceFault))]

    int CreateOrder(string currency, double amount);

 }

One thing you should note is that if you used the <serviceDebug> option and set the includeExceptionDetailInFault to true, the exception shielding will not work. So be sure to turn this option off.

Now, in order to receive this meaningful exception in the client, you should catch a FaultException<T> where T is the FaultContract use used.

try

{

    // Call the service method that has a fault contract on it

}

catch (FaultException<ServiceFault> ex)

{

    ServiceFault fault = ex.Detail;

    Console.WriteLine(fault.MessageText);

    Console.WriteLine(fault.Id);

}

You can download a sample project that shows this integration.

Enjoy!

Comments

Yosi Taguri said:

Great Post

# April 8, 2007 8:39 PM

Valdimar Thor said:

would exceptions be hadled any different is hosting was on the iis (WCF webservice) because I've not able to get this to work, the exception I get in the client is "The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error."

# May 7, 2007 10:08 PM

Guy Burstein's Blog said:

I've posted about the WCF Integration with Validation Application Block and the integration with Exception

# June 19, 2007 7:22 PM

Guy Burstein's Blog said:

Learn how to integrate WCF with Enterprise Library (Logging, Validation and Exception Handling)

# July 24, 2007 3:54 PM

Guy Burstein's Blog said:

Over the past year I've written almost 300 posts, and recently I took the time to see which posts were

# July 29, 2007 9:35 PM

Asif Prasla said:

Very nice post.

Thanks.

# September 19, 2007 8:02 PM

Zigman said:

# November 9, 2007 12:11 AM

Winston Johnston said:

hey - thanks for this post!

# December 20, 2007 4:33 AM

vivek said:

Could you please post the svcutil command param you used to generate the proxy. Because I am not able to expose the ServiceFault class to the client using the proxy generated by :

svcutil localhost/testService

It (proxy) does expose all the other members though. And I have decorated the ServiceFault with [DataContract].

Thnaks.

# January 7, 2008 9:40 PM

Pedram Rezaei's Ramblings said:

I put together the following brief description of WCF Error Handling and some possible best practices

# January 26, 2008 3:55 PM

Chanel said:

I just came into the webpage today, and it made me really happy to see that. My site chanel handbags chanelhandbagss.forum5.com/index.php

<a href="chanelhandbagss.forum5.com/index.php">chanel handbags</a>

[url=chanelhandbagss.forum5.com/index.php]chanel handbags[/url]

# January 28, 2008 4:54 PM

Patrick said:

Guy,

In WCF when I Validate an object through the [SelfValidation] attribute, it doesn't throw a FaultException<ValidationFault> like when I validate my object with the built-in property attributes like [StringLengthValidator].

Do you know why? Or what should I do to make my [SelfValidation] function throw a FaultException<ValidationFault>?

Thanks.

Patrick

# February 4, 2008 10:56 PM

ss said:

In my application the exception is not reaching the client.

Does anyone know the reason for ths?

# February 11, 2008 11:20 AM

Sofia said:

# February 18, 2008 8:58 PM

Poll said:

# March 3, 2008 12:37 AM

Kaj Bonfils said:

Hi,

Great post! But i have one problem. I keep getting a CommunicationException at the client in stead of the FaultException. Any clues?

Cheers,

Kaj

# March 5, 2008 11:45 AM

Kaj Bonfils said:

I figured it out... After several hours of looking with my blind eye, I found out that i didn't change the PostHandlingAction to ThrowNewException, so the original exception was thrown at the client.

I will beat myself up with a one of the big heavy WCF books until i learn to read what actually is written in the tutorial :-)

# March 5, 2008 4:42 PM

Viki said:

# March 7, 2008 5:59 PM

Den said:

# March 8, 2008 9:37 AM

Richard said:

# March 8, 2008 5:21 PM

Pol said:

# March 9, 2008 12:29 AM

Genri said:

# March 9, 2008 6:39 AM

Piter said:

# March 10, 2008 12:59 AM

Sem said:

# March 10, 2008 7:05 AM

Miki said:

# March 10, 2008 5:35 PM

Fiona said:

# March 11, 2008 12:21 AM

Suhail said:

Hi there,

I have a very peculiar problem. I have added both Exception shielding and validation for one of my interface. When i configure Exception Handling to shield any other type of exception except System.Exception the client get an unhandled exception which says "An error has occurred while consuming this service". If i use System.Exception type everything else works fine but i am not able to get the Validation Fault correctly but still things work while with any other exception nothing works.

If i remove either ValidationBehavior or ExceptionShielding attribute from my interface it starts working correctly.

Please do tell me that these two can work together and where i might be wrong.

Thanks in advance

Suhail

# March 12, 2008 5:35 PM

Bob said:

# March 13, 2008 6:45 AM

Kris said:

# March 13, 2008 2:22 PM

Niki said:

# March 14, 2008 2:39 AM

... said:

[URL=www.cedricleroy.com/hotel-copenaghen] hotel copenaghen [/URL]   <a href='www.cedricleroy.com/hotel-copenaghen'> hotel copenaghen </a>

# March 14, 2008 6:26 PM

... said:

[URL=www.huraiyth.com/amistad] amistad [/URL]   <a href='www.huraiyth.com/amistad'> amistad </a>

# March 15, 2008 12:23 AM

Richard said:

# March 15, 2008 4:59 AM

Feliks said:

# March 15, 2008 11:57 AM

... said:

[URL=www.huraiyth.com/film-cinema-anteprime] film cinema anteprime [/URL]   <a href='www.huraiyth.com/film-cinema-anteprime'> film cinema anteprime </a>

# March 15, 2008 5:30 PM

Sergei said:

# March 15, 2008 7:37 PM

... said:

[URL=www.betamate.com/masterizzatore-dvd-r] masterizzatore dvd r [/URL]   <a href='www.betamate.com/masterizzatore-dvd-r'> masterizzatore dvd r </a>

# March 15, 2008 11:27 PM

Sem said:

# March 16, 2008 2:18 AM

... said:

[URL=www.betamate.com/prestito-finanziario-prestito-personale] prestito finanziario prestito personale [/URL]   <a href='www.betamate.com/prestito-finanziario-prestito-personale'> prestito finanziario prestito personale </a>

# March 16, 2008 5:20 AM

Fedor said:

# March 16, 2008 8:47 AM

Ivan said:

# March 16, 2008 4:18 PM

... said:

[URL=www.betamate.com/meravigliosa-creatura] meravigliosa creatura [/URL]   <a href='www.betamate.com/meravigliosa-creatura'> meravigliosa creatura </a>

# March 16, 2008 6:15 PM

... said:

[URL=www.ncfliving.net/low-cost-web-hosting] low cost web hosting [/URL]   <a href='www.ncfliving.net/low-cost-web-hosting'> low cost web hosting </a>

# March 17, 2008 12:36 AM

... said:

[URL=www.ncfliving.net/globet] globet [/URL]   <a href='www.ncfliving.net/globet'> globet </a>

# March 17, 2008 6:42 AM

Frenk said:

# March 17, 2008 10:22 AM

... said:

[URL=http://www.key4fun.com/terapia] terapia [/URL]   <a href='http://www.key4fun.com/terapia'> terapia </a>

# March 17, 2008 1:42 PM

... said:

[URL=http://www.key4fun.com/hot-ass] hot ass [/URL]   <a href='http://www.key4fun.com/hot-ass'> hot ass </a>

# March 17, 2008 8:11 PM

... said:

[URL=http://www.fxtend.net/kyosho] kyosho [/URL]   <a href='http://www.fxtend.net/kyosho'> kyosho </a>

# March 18, 2008 2:37 AM

Piter said:

# March 18, 2008 6:59 AM

... said:

[URL=http://www.fxtend.net/second] second [/URL]   <a href='http://www.fxtend.net/second'> second </a>

# March 18, 2008 8:48 AM

... said:

[URL=www.michaelsteven.net/agenzia-modelli] agenzia modelli [/URL]   <a href='www.michaelsteven.net/agenzia-modelli'> agenzia modelli </a>

# March 18, 2008 4:57 PM

... said:

[URL=www.michaelsteven.net/agenzia-modelli] agenzia modelli [/URL]   <a href='www.michaelsteven.net/agenzia-modelli'> agenzia modelli </a>

# March 18, 2008 4:57 PM

Semen said:

# March 18, 2008 5:08 PM

... said:

[URL=www.michaelsteven.net/rigenerare-toner] rigenerare toner [/URL]   <a href='www.michaelsteven.net/rigenerare-toner'> rigenerare toner </a>

# March 19, 2008 1:58 AM

... said:

[URL=www.youngamericansfund.com/diocesi-di-milano] diocesi di milano [/URL]   <a href='www.youngamericansfund.com/diocesi-di-milano'> diocesi di milano </a>

# March 19, 2008 8:42 AM

... said:

[URL=www.youngamericansfund.com/creme-anticellulite] creme anticellulite [/URL]   <a href='www.youngamericansfund.com/creme-anticellulite'> creme anticellulite </a>

# March 19, 2008 3:25 PM

Fred said:

# March 19, 2008 4:49 PM

Dima said:

# March 21, 2008 5:22 AM

Nina said:

# March 21, 2008 1:46 PM

Victoria said:

# March 21, 2008 11:41 PM

Fred said:

# March 22, 2008 8:16 AM

Alize said:

# March 23, 2008 3:18 AM

Goofi said:

# March 25, 2008 8:41 PM

Natasha said:

# March 27, 2008 4:18 PM

Victor said:

# March 28, 2008 1:33 PM

Piter said:

# March 29, 2008 5:19 AM

Linda said:

# March 30, 2008 4:09 AM

Nica said:

# March 30, 2008 11:15 AM

Sergio said:

# March 31, 2008 3:59 AM

Bobi said:

# March 31, 2008 12:27 PM

Alisa said:

# April 1, 2008 7:24 AM

Robert said:

# April 1, 2008 6:29 PM

Patrik said:

# April 5, 2008 5:13 PM

Saveli said:

# April 6, 2008 8:02 PM

tusanesen said:

I couldnt run your sample project as it s supposed. client doesnt get FaultException<ServiceFault> but only FaultException. So u luckily catched the most generic exception type to catch something whether or not "meaningful" :)

I spent half a day with this problem. when I see u post a sample project I hoped its only my problem but as I see, its not.

do u have an idea abt what the problem is ?

# May 7, 2008 12:54 PM

tusanesen said:

I just realized that when I add ExceptionHandling.Wcf dll, which is replaced to the GAC when I installed entLib., as a reference to the Servicecontracts project, its not working right. (the problem I explained above occurs). If I add the ExceptionHandling.Wcf project to your sample solution and add it as a reference to the serviceContracts project, its working correctly.

Maybe u also experienced same problem and added the projects to the solution instead of only released dlls. I would appreciate if somebody comments abt this ?

# May 7, 2008 7:18 PM

Intatnindmits said:

I found this page in the previous story What it mean ?

http://universit162.hit.bg

http://wateribmk535.hit.bg

Would you like to criticize and witter on till the cows come homey side the fad with me? I'll be hosting my premier-yet FW online fash bullshit flirt Friday at 12pm, answering any questions you weight obtain approximately elegance conundrums, where to come across any special items, what to utilization decided items with, or still objective to talk hither the obstruct that makes us swoon.

# December 31, 2008 8:53 PM

Mickey said:

I am using an ASMX service in my WCF service library. I am adding ASMX services as "Service References" in my WCF service library. I want to catch the soap exceptions thrown by the ASMX services. Can you please suggest me how can I do that?

# January 7, 2009 2:16 PM

DrFooMod2 said:

This creates a message named:

JobsService_FindJobs_ServiceFaultFault_FaultMessage

This is pretty ugly.  Any way to clean this up?

# February 13, 2009 4:24 PM

Nirnay Bansal said:

I am getting xml parse error in ex. Somebody knows why.

thanks, Nirnay

www.techvalens.com

# July 16, 2009 7:30 PM

SerialHobbyist said:

A great article.  I spent all yesterday morning trying to get this working to no avail.  I was spitting nails by the end of it.  So I walked away and came back today and found this article.  I started from scratch based on this and now it works.  I THINK the only difference was: ThrowNewException.  Oh well, we live and learn.  I also liked your article on Code Project (www.codeproject.com/.../WCFVAB.aspx) and am getting on great.

Thanks for the great work you do.

# July 26, 2009 10:30 PM

WCF: SOAP Fault or normal Exception(s) in DataContract class - Programmers Goodies said:

Pingback from  WCF: SOAP Fault or normal Exception(s) in DataContract class - Programmers Goodies

# November 11, 2011 2:35 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: