I have the following code in WCF service to throw a custom fault based on certain situations. I am getting a "The creator of this fault did not specify a Reason" exception. What am I doing wrong?
//source code if(!DidItPass) { InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started"); throw new FaultException<InvalidRoutingCodeFault>(fault); } //operation contract [OperationContract] [FaultContract(typeof(InvalidRoutingCodeFault))] bool MyMethod(); //data contract [DataContract(Namespace="http://myuri.org/Simple")] public class InvalidRoutingCodeFault { private string m_ErrorMessage = string.Empty; public InvalidRoutingCodeFault(string message) { this.m_ErrorMessage = message; } [DataMember] public string ErrorMessage { get { return this.m_ErrorMessage; } set { this.m_ErrorMessage = value; } } }
After some addtional research, the following modified code worked:
if(!DidItPass) { InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started"); throw new FaultException<InvalidRoutingCodeFault>(fault, new FaultReason("Invalid Routing Code - No Approval Started")); }
The short answer is you are doing nothing wrong, just reading the results incorrectly.
On the client side when you catch the error, what is caught is of the type System.ServiceModel.FaultException<InvalidRoutingCodeFault>
.
Your InvalidRoutingCodeFault
object is actually in the .detail
property of the FaultException. SO....
// client code
private static void InvokeMyMethod() { ServiceClient service = new MyService.ServiceClient(); try { service.MyMethod(); } catch (System.ServiceModel.FaultException<InvalidRoutingCodeFault> ex) { // This will output the "Message" property of the System.ServiceModel.FaultException // 'The creator of this fault did not specify a Reason' if not specified when thrown Console.WriteLine("faultException Message: " + ex.Message); // This will output the ErrorMessage property of your InvalidRoutingCodeFault type Console.WriteLine("InvalidRoutingCodeFault Message: " + ex.Detail.ErrorMessage); } }
The Message property of the FaultException is what is displayed on the error page so if it's not populated like in John Egerton's post, you will see the 'The creator of this fault did not specify a Reason' message. To easily populate it, use the two parameter constructor when throwing the fault in the service as follows, passing your error message from your fault type:
InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started"); throw new FaultException<InvalidRoutingCodeFault>(fault, new FaultReason(fault.ErrorMessage));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With