WCF FaultException inconsistency - c#

I have a WCF service that throws FaultExceptions when something goes wrong. Some of the error classes being thrown works just fine, yet some of the other doesn't work at all and give the following error:
An error occured while receiving the HTTP response to http://localhost/MyService. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down).
With an inner exception saying
The underlying connection was closed: An unexpected error occurred on a receive.
My code works thusly:
Server
public Stream DoSomething() {
if (someCondition) {
if (fileExists) {
return new Stream(); // I know I can't do this, but for example purpose only :)
}
throw new FaultException<System.IO.FileNotFoundException>(new FileNotFoundException());
}
throw new FaultException<MyException>(new MyException());
}
Exception class
public class MyException: Exception
{
}
Client
try {
wcfClient.DoSomething();
} catch (FaultException<FileNotFoundException>) {
// This works just fine
} catch (FaultException<MyException>) {
// This gives the error listed above
}
Both FileNotFoundException and MyException are set up in the contract:
[FaultContract(typeof(FileNotFoundException))]
[FaultContract(typeof(MyException))]
Why does FaultException<FileNotFoundException> work as expected, but not FaultException<MyException>?
If I remove Exception inheritance from MyException everything works as it should (but I want consistency, so I want it to be an actual exception). There is no change if Exception inheritance is left in, but it is decorated with [DataContract].
Why is that? FileNotFoundException inherits from Exception too. One works, the other doesn't. Frustrating!
P.S.: Both the server and the client share the same assembly the interfaces and classes are defined in, so there shouldn't be any contract mismatches.

Your exception should probably be [Serializable]. I think that would solve your problem already.
As a best practice for Exceptions you should also implement the three constructors.

Related

Wcf Error handling using IErrorHandler interface

I have a question regarding WCF fault exceptions. I am implementing the IErrorHandler interface and creating a FaultException.
My question is this: When am I creating a FaultException, is there a pattern that I must follow to send a friendly error message to the client?
I log the actual exception using the HandleError method to the database and creating a FaultException in the ProvideFault method.
Given delow, there is my sample implementation of IErrorHandler interface.
public bool HandleError(Exception error)
{
System.Diagnostics.Debug.WriteLine(error.Message);
// Log the error to the Db
return true;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
// Here is a sample that I was playing with.
MessageFault faultException;
if(error is DataException)
faultException = new FaultException<string>(ErrorStrings.DatabaseOpenError, new FaultReason(ErrorStrings.DatabaseOpenError)).CreateMessageFault();
else if (error is NullReferenceException)
faultException = new FaultException<string>(ErrorStrings.NullDataError, new FaultReason(ErrorStrings.NullDataError)).CreateMessageFault();
else
faultException = new FaultException<string>(ErrorStrings.GeneralError, new FaultReason(ErrorStrings.GeneralError)).CreateMessageFault();
fault = Message.CreateMessage(version, faultException, "");
}
I need some clarity on what exactly has to be done inside ProvideFault method to return a friendly Fault to the user. I am also planning to use localization to display errors. Not sure if this will be done by the client or if service should send localized messages.
Based on what I read, I should not send information of the stack from the error or EntityFramework errors, like EntityValidation errors and so on, to the client due to security reasons.
In this case, will I need to check for the type of exception and mine the details to be more appropriate before sending to the client?
The main requirement is to use the FaultContractAttribute so WCF understands the service contract being fulfilled. Please see http://msdn.microsoft.com/en-us/library/ms752208(v=vs.110).aspx
WCF will then also make sure your WSDL reflects your fault contracts.

Exceptions in validation

I currently have some code that delibratly throws an exception if the user sends me data that fails validation (see below). I like it because im sure any errors in the application are caught and handled. A am however worried the code being slow as throwing exceptions takes a lot of memory. Im also worried it might be "bad code". Whats your advice? Thanks
public class BTAmendAppointmentRequest
{
public DataLayer.WebserviceMessage AddBTAmendAppointmentRequest(DataLayer.BTAmendAppointmentRequest req)
{
DataLayer.WebserviceMessage rsp = new DataLayer.WebserviceMessage();
try
{
if (!String.IsNullOrEmpty(req.AppointmentReference))
req.AppointmentReference = req.AppointmentReference.Trim();
if (req.OrderRequestID < 1 || string.IsNullOrEmpty(req.AppointmentReference))
{
throw new Exception("Amend appointment failed, you must supply a valid appointment reference and order reference");
}
...Do other stuff
}
catch (Exception ex)
{
rsp = new Service.WebserviceErrorMessage(ex);
}
return rsp;
}
}
If you are expecting these errors, you should return error messages to the user, not throw exceptions.
Reserve exceptions to exceptional situations.
Apart from being expensive, the meaning of an exception, the semantics are that of something exceptional having happened. Validation failing is not exceptional, it is expected.
Having said that, seeing as you are on a web service, an exception is a reasonable thing to do, assuming you also validate before the service call. It is reasonable since a web service can be called by anything - validation may not have happened, and such errors should be exceptional. Additionally, at least with .NET web services, web exceptions are probably the best way to communicate such things back to the client.
Exceptions should be considered as last resort error trap. They should be "exceptional". Data input errors are not exceptions - they are very common, expected events. You shoudl handle validation issues with validation controls or processes, that handle them - display an error message and do not let the processing continue.
Your other problem is that you cannot easily do full form validation if the first error you encounter throws an exception. If I was filling out a form where each error was separately highlighted, I would give up very quickly. You need to be able to validate and display ALL errors on a page, and not permit progress without validation succeeding.
I tend to agree with Oded in that exceptions should only be used for stuff you aren't expecting. The other way to look at it is with using an errors collection, you are able to validate a larger batch instead of throwing an exception on the first problem. This can be more usable for the person consuming your service.
In the case of web services, I would package the entire response in a custom response object, which features a return code. This allows you to have a return code of error, and then encapsulate an errors collection in the response object.

WCF web service call - which exception(s) to catch?

I have a program that calls an external web service, and I want to present the user with a friendly dialog if e.g. the server is down, someone cut the cable etc. Assuming the following code
try {
client.MyWebService()
}
catch(? ex)
{
// display friendly dialog explaining what went wrong
}
what exception(s) should I put in place of the question mark in the code? It is kind of hard to actually test situations like this when everything is working smoothly and I have no control over the external part, so some insight would be appreciated.
Thanks!
The first thing to do is take advantage of the .Faulted event on your proxy, which you can wire up like this:
((ICommunicationObject)client).Faulted += new EventHandler(client_Faulted);
In your client_Faulted event handler you can then try re-connecting, or shifting to a backup server, or disabling the UI, logging the error, or displaying a message there.
It's obviously still good practice to wrap each call in a try-catch as well, but the .Faulted event can let you deal with most channel problems even earlier.
As for the exception itself, you can have your service throw a FaultException that gets passed back to the client with the details you provide. See an example of its use at this blog posting.
You won't get a FaultException if the channel itself fails (FaultException is a way for the server to communicate its own internal faults to the client).
For channel faults, you may get a CommunicationException or TimeoutException.
Finally, take a look at this project on Codeplex for generating Exception Handling WCF proxies. It may give you a more flexible way of handing faults.
It's not really the client's job to provide as much detail as possible. The maximum amount you really have to provide at the client side is as much as you get back in your exception.
var userName = "bob";
try
{
client.MyWebService(userName);
}
catch(Exception ex)
{
//Maybe we know WellKnownExceptions and can provide Foo advice:
if (ex is WellKnownException)
{
Console.WriteLine("WellKnownException encountered, do Foo to fix Bar.");
}
//otherwise, this is the best you can do:
Console.WriteLine(string.Format(
"MyWebService call failed for {0}. Details: {1}", userName, ex));
}
I was asking the same question, as I have to implement some exception handling on web services calls at my client application, so I ended up here. Although it's an old question, I'd like to give my two cents, updating it a little bit.
The answer given by C. Lawrence Wenham was already very good and points to some interesting information, although the blog link is broken and Codeplex is now archived.
I found those articles very valuables:
Sending and Receiving Faults
https://learn.microsoft.com/en-us/dotnet/framework/wcf/sending-and-receiving-faults
Expected Exceptions
https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/expected-exceptions
And this article from Michèle Leroux Bustamante (apparently the creator of the Exception Handling WCF Proxy Generator CodePlex project) is very insighful also:
An Elegant Exception-Handling Proxy Solution
http://www.itprotoday.com/microsoft-visual-studio/elegant-exception-handling-proxy-solution
I'm still studying the subject but I guess I'll use a lot of ideias from Michèle. I'm just a little bit concerned about using reflection to call the web service's methods, but I wonder if this would have any impact in such kind of operation, that is inherently slow already.
Just to answer here explicitly what was asked originally, which are the exceptions that could be tested against a web service call:
string errorMessage = null;
// A class derived from System.ServiceModel.ClientBase.
MyWebService wcfClient = new MyWebService();
try
{
wcfClient.Open();
wcfClient.MyWebServiceMethod();
}
catch (TimeoutException timeEx)
{
// The service operation timed out.
errorMessage = timeEx.Message;
}
catch (FaultException<ExceptionDetail> declaredFaultEx)
{
// An error on the service, transmitted via declared SOAP
// fault (specified in the contract for an operation).
errorMessage = declaredFaultEx.Detail.Message;
}
catch (FaultException unknownFaultEx)
{
// An error on the service, transmitted via undeclared SOAP
// fault (not specified in the contract for an operation).
errorMessage = unknownFaultEx.Message;
}
catch (CommunicationException commEx)
{
// A communication error in either the service or client application.
errorMessage = commEx.Message;
}
finally
{
if (wcfClient.State == CommunicationState.Faulted)
wcfClient.Abort();
else
wcfClient.Close();
}
As stated by the articles, the order the exceptions are catched is important, since FaultException<TDetail> derives from FaultException, and FaultException derives from CommunicationException.

Unhandled exception using FaultException<T> with WCF and WP7 App

I am consuming a WCF service from a WP7 app. Both are in a single VS solution. Everything worked fine until I tried to pass back a FaultException.
When throwing the FaultException from my WCF service, I receive the message "An unhandled exception of type 'System.ServiceModel.FaultException`1' occurred in System.ServiceModel.dll" on the EndInvoke in my proxy. If I hit continue, the exception does not bubble up. My handler code is never hit.
I believe I have everything wired up properly. I've seen plenty of examples, as I've spent an entire day scouring the web for help with this issue. If I stop throwing the FaultException, my application works fine.
In the VS Debug > Exceptions dialog, I have tried disabling FaultException and FaultException'1 under CLR/System.ServiceModel. I have also tried going to Tools > Options, Debuggung > General and turning off "Enable the exception assistant" and "Enable Just My Code (Managed only). None of these has enabled the exception to bubble up to my calling method in the app.
Interface code --
[OperationContract]
[FaultContract(typeof(NotAuthorizedException))]
List<MyResult> GetValues(DateTime beginDate, DateTime endDate);
Exception type --
[DataContract]
public class NotAuthorizedException
{
[DataMember]
public string Message { get; set; }
}
Server code to throw exception --
throw new FaultException<NotAuthorizedException>(
new NotAuthorizedException(),
new FaultReason("Not authorized."),
new FaultCode("Sender"));
Client call to WCF service --
try
{
MyServiceClient myService = new MyServiceClient();
myService.GetValuesCompleted += new EventHandler<GetValuesCompletedEventArgs>(myService_GetValuesCompleted);
myService.GetValuesAsync(DateTime.Now, DateTime.Now.AddMonths(6));
}
catch (FaultException<NotAuthorizedException>)
{
//handle error here
}
Where it breaks (in Reference.cs) --
System.Collections.ObjectModel.ObservableCollection<Namespace.MyService.MyResult> _result = ((System.Collections.ObjectModel.ObservableCollection<Namespace.MyService.MyResult>)(base.EndInvoke("GetValues", _args, result)));
The proxy code is the unaltered code generated from "Add Service Reference" menu item.
It has to be something simple, but I'm just not seeing it!
I believe you should catch the FaultException<NotAuthorizedException>
at myService_GetValuesCompleted instead of where you are doing it now

Proper catching of specific exceptions through web service

I am currently using a C# .NET Service in our client program. As part of the server design, several custom made exceptions are thrown to indicate specific errors (as in any normal desktop program).
The problem is that the Web Service catches these errors and serializes them into a FaultException, with the actual exception (like NoRoomsAvailableException) written in the Message field.
My question is whether there is a best practice for handling these errors. We have just begun working on this, and we would probably do some text pattern matching to pull out the exception type and error message, but it seems like a hacky way to do it, so any "clean" way of doing it would be much appreciated.
The proper way would be to define fault contracts. For example in your web service you could do the following:
[DataContract]
public class NoRoomsAvailableFaultContract
{
[DataMember]
public string Message { get; set; }
}
Next you declare this contract for a given service operation
[ServiceContract]
public interface IMyServiceContract
{
[OperationContract]
[FaultContract(typeof(NoRoomsAvailableFaultContract))]
void MyOperation();
}
And you implement it like so:
public class MyService : IMyServiceContract
{
public void MyOperation()
{
if (somethingWentWrong)
{
var faultContract = new NoRoomsAvailableFaultContract()
{
Message = "ERROR MESSAGE"
};
throw new FaultException<NoRoomsAvailableFaultContract>(faultContract);
}
}
}
In this case the NoRoomsAvailableFaultContract will be exposed in the WSDL and svcutil.exe could generate a proxy class. Then you could catch this exception:
try
{
myServiceProxy.MyOperation();
}
catch (FaultException<NoRoomsAvailableFaultContract> ex)
{
Console.WriteLine(ex.Message);
}
darin has the correct answer. I'll only say explicitly what he implies: web services do not pass exceptions. They return SOAP Faults. If you define your faults properly, as he does, then you get to throw FaultException<fault>. This will become a SOAP Fault with fault in the detail element. In the case of a .NET client, this will then be turned into a FaultException<fault>, which you can catch.
Other platforms may handle this somewhat differently. I've seen IBM's Rational Web Developer generate Java proxy code that creates a separate exception for each declared fault. That was a version before Java generics, so maybe by now it does the same thing as .NET does.

Categories

Resources