It's Your Fault!

In talking to people about WCF, I've noticed that a lot of people, new to WCF and not, have not realized that WCF has the ability to send rich fault information back to the client by using a Fault Contract. It's very easy. In fact, you can do it in four steps...

Step 1: Admit your faults

The first thing we need to do is determine what kind of information we want to return back to the client and create a data contract that contains that information. You may have several kinds of fault classes, and you should so that you can return specific types of information for specific faults. Kinda like why there isn't just one Exception class in .NET. Although these are data contracts, you should not use them for anything other than sending faults back to the client. Here's a sample fault class:

[DataContract]
    public class MyFault
    {
        private string _message = string.Empty;

        public MyFault(string message)
        {
            _message = message;
        }

        [DataMember]
        public string Message
        {
            get
            {
                return _message;
            }
            set
            {
                _message = value;
            }
        }
    }

Like any .NET class, you can create a fault class the inherits from another .NET class, BUT that class also needs to be a data contract and be a known type.

Step 2: Find where you may go wrong

Next, we need to let WCF know where these faults might be coming from. This is done at the operation in the service contract. You simply use a FaultContract attribute which lets WCF know what kind of possible fault class to expect:

[ServiceContract]
public interface IFaultyService
{
    [OperationContract]
    [FaultContract(typeof(MyFault))]
    void ThrowMeAnError();
}

You can specify as many faults for the operation as you like, simply add more FaultContract attributes:

[ServiceContract]
public interface IFaultyService
{
    [OperationContract]
    [FaultContract(typeof(MyFault))]
    [FaultContract(typeof(MyOtherFault))]
    [FaultContract(typeof(YetAnotherFault))]
    void ThrowMeAnError();
}

Step 3: The throw...

Throwing faults from a service is a little different than throwing them from C# or VB code. We need to enclose our fault class in a FaultException<T>, which represents a SOAP exception. This is just as easy as the other steps:

throw new FaultException<MyFault>(new MyFault("This is a fault"), "Demonstration");

The second argument, in this case "Demonstration" is the reason for the fault. And yes, "reason" is the attribute name of the fault too. This can either be a string or a FaultReason object which allows you to send more detailed information about the exception.

Step 4: ... and the catch

If you've done everything correctly, when you generate a reference to your service, in addition to the normal proxy information, you should have a class representing the data contract you created for your fault class. Catching this exception on the client side is similar to throwing it on the server side. It will come wrapped in a FaultException<T> and you will need to specify that to catch it correctly:

.
.
.
catch(FaultException<MyFault> itsMyFault)
{
    Console.WriteLine("MyFault was caught");
    Console.WriteLine(string.Format(@"Message: {0}", itsMyFault.Detail.Message));
    Console.WriteLine(string.Format(@"Reason: {0}", itsMyFault.Reason));
}
.
.
.

As you can see, getting the reason is pretty straight forward. Our message, and any other field me might have added, will be accessible as a member of the Detail child object of our fault.

That's it. See, nothing to it.

Actually, this rabbit hole does go a little deeper, but this should be enough to get you all started with capturing rich error information from your services.

Print | posted on Thursday, April 17, 2008 7:52 PM

Feedback

# re: It's Your Fault!

left by Matt Casto at 4/18/2008 8:10 AM Gravatar
Excellent walkthrough.

Are you going to go into creating an ErrorHandler behavior?

Also, you must tell me how you got code formatting in your blog to show up in Google Reader!

# re: It's Your Fault!

left by James at 4/18/2008 3:18 PM Gravatar
I'm looking at putting an EventHandler behavior post together, but there's a lot in the queue right now.

There is a tool you can download for Windows Live Writer called VS Paste. You can get it at http://tinyurl.com/6alkjk

# re: It's Your Fault!

left by Drug Treatment Center at 3/12/2010 12:01 AM Gravatar
Nice information, valuable and excellent, as share good stuff with good ideas and concepts

# re: It's Your Fault!

left by LieYuan0415 at 8/3/2010 10:34 PM Gravatar

Monogram Canvas materials, MCTS Certification
both of which were first used in the CompTIA Certification late 19th century. All of the company's products exhibit the eponymous The company markets its product through its own stores loca "We are liking to carrying the CompTIA Certification
Coach outletwhich is popular in the world and love by many people. Please don't miss the Coach handbags. CompTIA Certification
Some customers do not know how many information were offered online. The Coach OP Art Bags in the low price and elegance, convenience and style. This is the magic of Coach! Buy CompTIA Certification
Coach Sunglasses with the discount price in the store. Usually, for an common family the Coach Kiristin bags really is the big pending. Then the cheap Coach bags

# re: It's Your Fault!

left by CDPdiazhuLJPYLL701 at 8/4/2010 12:21 AM Gravatar
The ActualCerts Microsoft MCITP Certification
2008 practice exam is the ultimate in prep tools, and can be complimented with a variety of other tools like lab Microsoft MCSE 2008 simulation questions, interactive or static Microsoft MCSA Certification
2008 study guide notes, or the customizable Microsoft MCSA Certification
2008 training course for the mobile trainee. There is no shortage of valuable Microsoft MCSE 2008 tips bringing you instant MicrosoftMCSA Certification
2008 tests success that you can feel. No other online Microsoft MCSE Certification
2008 tutorial can make these claims of make the guarantee you get with ActualCerts.
More than Microsoft MCSE 2008 Boot Camps

# re: It's Your Fault!

left by lyAnswer at 8/4/2010 2:56 AM Gravatar
Considered a sign of good luck and something to keep your heart light, this sterling MCITP Certification Ladybird charm with red and black enamel accents makes a colorful addition to your collection MCSE Certificationfrom MCSE Certification. You prefer idyllic scenery to City View, so you go to take in the Ladybug MCSE Certificationcharm of this beautiful scene. I believe you have MCSE Certificationa different of feeling.

# re: It's Your Fault!

left by sisi at 8/6/2010 1:49 AM Gravatar
Each replica watches rep1ica.com replica a lange & sohne replica watches product replica watches 4u.com/bracelets-c-180.html replica watch bracelets replica burett design style replica watches rings are differentrep1ica.com replica accutron replica watch find the replica watch charms on sale jewelry Replica Breitling Airwolf Replica Watches Cheap belong to you replica a lange & sohne Vogue replica watch watcopy.com replica burett replica watch of happiness ofbuy silver-chain replica accutron silver bead chain crystal series Replica Rolex Datejusts top sweetie Replica A Lange & Sohne Autumnwonderful Replica Aigner ring charm Memories Replica Breitling Chronomat Evolution Watches butterfly valley top .com/bracelets-c-180.html Manual, mysterious luxury

# re: It's Your Fault!

left by Kingkle at 8/8/2010 2:17 AM Gravatar
Begin to build yourreplica Cartier watches
confidence, and work throughHublot replica watches
problems rather than avoid them. Remember replica Omega watches
that power is not necessarily controlOmega replica watches
over situations, but the ability to deal with Rolex replica watches
whatever comes your way.

# http://www.replica-king.com

left by maggie at 8/19/2010 4:57 AM Gravatar
Do you like the Relica watchesReplica Cartier Roadster Watches?It's a wide variety,Replica Cartier Santosappearance beautifulReplica Cartier Pasha Watches, noble and occasion.Replica Cartier Santos

# re: It's Your Fault!

left by coach bags at 8/22/2010 11:31 PM Gravatar
Market is flooded UGG Boots on Sale with different types UGG Classic Short Boots of leather UGG Classic Tall Boots bags and wallets UGG Argyle Knit Boots. When it comes to UGG Bailey Button Boots choosing a leather bags UGG Classic Cardy Boots or wallet, UGG Baby Coach Leather bags Kids UGG Boots and wallets are Timberland Shoes something that Shoes Timberland you can rely Vibram Five Fingers on. Coach leather bags Vibram FiveFingers and wallets a have Discount Vibram Five Fingers been in the Discount Vibram FiveFingers market since Discount Vibram 1940s. These leather bags Prada Shoes have made a distinguished Gucci Shoes in the market. Not only Coach Bags in terms of quality these leather Coach New Style Bags are popular for both Coach New Style Bags and elegance. Before you go to purchase a leather prada Bags, make up your Gucci Bags which kind of Chanel Bags you want to go for Louis Vuitton Bags. Since these wallets are Jimmy Choo Bags in different colors, Tous Bags and design MBT Shoes you are a MBT Shoes on sale confused as to which MBT Sandals to buy MBT Shoes Outlet. Here are a MBT Sandals on Sale tips to MBT Outlet choose which for MBT Men’s Shoes who are fond of carrying MBT Women’s Shoes all the time, going for a Outlet MBT leather bag also. Ray Ban Sunglasses or bag suits Oakley Sunglasses. Here are lots of Chanel Jewelry first of all Chanel Jewelry Outlet if you are Jewelry Outlet kind of line, go for the Jewelry Online Outlet which have more credit Cartier Jewelry compartments.

# re: It's Your Fault!

left by coach bags at 8/22/2010 11:31 PM Gravatar
Market is flooded UGG Boots on Sale with different types UGG Classic Short Boots of leather UGG Classic Tall Boots bags and wallets UGG Argyle Knit Boots. When it comes to UGG Bailey Button Boots choosing a leather bags UGG Classic Cardy Boots or wallet, UGG Baby Coach Leather bags Kids UGG Boots and wallets are Timberland Shoes something that Shoes Timberland you can rely Vibram Five Fingers on. Coach leather bags Vibram FiveFingers and wallets a have Discount Vibram Five Fingers been in the Discount Vibram FiveFingers market since Discount Vibram 1940s. These leather bags Prada Shoes have made a distinguished Gucci Shoes in the market. Not only Coach Bags in terms of quality these leather Coach New Style Bags are popular for both Coach New Style Bags and elegance. Before you go to purchase a leather prada Bags, make up your Gucci Bags which kind of Chanel Bags you want to go for Louis Vuitton Bags. Since these wallets are Jimmy Choo Bags in different colors, Tous Bags and design MBT Shoes you are a MBT Shoes on sale confused as to which MBT Sandals to buy MBT Shoes Outlet. Here are a MBT Sandals on Sale tips to MBT Outlet choose which for MBT Men’s Shoes who are fond of carrying MBT Women’s Shoes all the time, going for a Outlet MBT leather bag also. Ray Ban Sunglasses or bag suits Oakley Sunglasses. Here are lots of Chanel Jewelry first of all Chanel Jewelry Outlet if you are Jewelry Outlet kind of line, Jewelry Online Outlet which have more credit Cartier Jewelry compartments.

# re: It's Your Fault!

left by fm stereo transmitter at 8/24/2010 2:14 AM Gravatar
As we all know Tiffany is a symbol of status and fortune with its high quality pop classic style and tiffany lighting pendants also expensive price which makes most of us flinch. But now it`s not a dream which is quite far from you any more. To get a affectionate Tiffany, You only need to pay 1% of the original price. And tiffany inspired neckalce with the pure silver jewelry decorating a gorgeous painting for you--the beauty in the painting will be presented immediately. Talking about the pure silver accessories,tiffany silver sets on sale you need to know something about the pure silver. tiffany cuff links on sale Pure silver is not absolutely pure. in fact, it stands for a 925 pure silver which means the silver productions which’s purity of silver are 92.5%. 925 here represents the purity of silver. This is required lowest purity of silver productions while the purity of 999 gold. For foot silver is too soft and it’s easy to be oxidized, since Tiffany company created 925 silver, it’s thought to be the lowest standard of pure silver.
welcome to my blog tiffany rings.
Tiffany On Sale directly sellcheap silver Tiffany Necklacesjewelry. Cheap price + High Quality + Brand New. Also provides our customers with various kinds of tasteful silver necklaces, they are so fashion and classic, and welcomed by most people.
tiffany silver charm bracelets
Tiffany inspired rings
Discount tiffany earrings
welcome to my blog tiffany rings.

# re: It's Your Fault!

left by Wanling at 8/24/2010 11:40 PM Gravatar

Our Breitling Watches are as same as original watches with best price, high quality & superb workmanship. It is good in material, fashionable in design, and superb in workmanship. Buy Hublot Watcheswhich posses all functions and Audemars Piguet Watchesa Watches
the original. We can assure you that these designer Tag Heuer Monaco Watches can not give you not only the look of the real, but also the feel of the real for! Hublot Watches will make you popular Japan Rolex Datejustand good-looking person!Patek Philippe Replica Watches Audemars Piguet Replica Watches IWC Replica Watches
Frank Muller Replica Watches Chanel Replica Watches

# Miss Mughal

left by Sarah Mughal at 8/26/2010 1:32 PM Gravatar
Sarah Mughal | - | | - | Miss Mughal
Information Islam | - | | - | Islam is the religion of Peace.
Convert to Islam | - | | - | How to convert to Islam
Wild Plants | - | | - | Medicinal Native Plants of Pakistan, Wild plants of rural and arban areas of pakistan
Introduction to Botany | - | | - | Study of plants is called botany.
Plant Flowering | - | | - | Most likely plants and flowers
Information Botany | - | | - | The branch of biology that studies plants.
SEO News | - | | - | Search Engine Optimization , Bing, Google, Yahoo.

# re: It's Your Fault!

left by pangsiyan at 8/26/2010 11:08 PM Gravatar
4.Your personal instructor walk you step-by-step through various ccie lab training.Experience our mock labs which highly reflect the most current actual ccie sp lab
.Recommended for CCIE Exams candidates who need in-depth understanding on each lab topic.

# re: It's Your Fault!

left by cheap nike air max shoes at 9/1/2010 2:52 AM Gravatar
People running and playing ball frequently have to decide which shoe they would prefer to go to purchase. Nike have a reputation of producing high-quality and nice looking shoes. The great sneaker created by Nike company deserve to nike airmax be recommended, for the sports equipment is superior to some. Running shoes need to have certain features if they are considered to be good. Running shoes need to have certain features if they are considered nike air max 90 to be good. Being light weight and comfortable, fitting good, offering high performance and great traction should all be taken into account. The Nike Air Max, they are able to do these extremely well. By the advanced Nike air max 95 Air Max Cushioning system that found under the shoe performing perfectly at absorbing the shock generated from the running impact, the shoe is quite comfortable cheap air max that it help you greatly on my runs. The shoe also fits well because of the great lacing system--an upper specialized nike air max uk in designing for runners. The upper is lightweight and it is mostly courtesy of a breathable mesh material, so a wonderful running experience generated. Its outsole also give you the excellent traction. As a result of a good rubber outsole the shoe has a great durability as well. Besides, its reasonable price reveal that it has the consumer in mind. For this reasons, it becomes a popular equipment among gabber music fans and an agreeable item in Hip Hop Culture.

#  re: It's Your Fault!

left by Callaway Diablo Edge Driver at 9/2/2010 5:28 AM Gravatar
Happy to have found this post.It's interest.
Thanks for your blog.I just stumbled upon your blog.
Title  
Name
Email (never displayed)
Url
Comments   
Please add 8 and 8 and type the answer here: