Wcf Error handling using IErrorHandler interface - c#

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.

Related

WCF FaultException inconsistency

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.

WCF routing service channel shutdown

The error message is following:
This channel can no longer be used to send messages as the output
session was auto-closed due to a server-initiated shutdown. Either
disable auto-close by setting the
DispatchRuntime.AutomaticInputSessionShutdown to false, or consider
modifying the shutdown protocol with the remote server.
It happens, when I create a web request to a WCF router (wsHttpBinding or BasicHttpBinding to NetTcpBinding) and the router then requests WinService. Once the WinService throws an Exception, the next requests gives the error message above. It is created by the WCF router.
There was no solution anywhere, I've spend days finding one.
Links to similar problems without solution:
WCF Communication error occurs randomly and impossible to catch the reason why
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/3f19cdaa-f426-4902-a93a-2654c7f19788/
The working solution I did is following:
Do not throw an Exception, throw FaultException
How to do that:
On the WinService interface define a response code enum (example following)
[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.2152")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "blah")]
public enum ErrorCode
{
ERROR
}
or just
public enum ErrorCode
{
ERROR
}
then instead of an Exception throw FaultException using defined enum:
throw new FaultException(ErrorCode.ERROR, new FaultReason("blah"), new FaultCode("Sender"));
And that's it! Now you can send request that generate this exception and it doesn't close the channel

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.

How to produce an HTTP 403-equivalent WCF Message from an IErrorHandler?

I want to write an IErrorHandler implementation that will handle AuthenticationException instances (a proprietary type), and then in the implementation of ProvideFault provide a traditional Http Response with a status code of 403 as the fault message.
So far I have my first best guess wired into a service, but WCF appears to be ignoring the output message completely, even though the error handler is being called.
At the moment, the code looks like this:
public class AuthWeb403ErrorHandler : IErrorHandler
{
#region IErrorHandler Members
public bool HandleError(Exception error)
{
return error is AuthenticationException;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
//first attempt - just a stab in the dark, really
HttpResponseMessageProperty property = new HttpResponseMessageProperty();
property.SuppressEntityBody = true;
property.StatusCode = System.Net.HttpStatusCode.Forbidden;
property.StatusDescription = "Forbidden";
var m = Message.CreateMessage(version, null);
m.Properties[HttpResponseMessageProperty.Name] = property;
fault = m;
}
#endregion
}
With this in place, I just get the standard WCF html 'The server encountered an error processing the request. See server logs for more details.' - which is what would happen if there was no IErrorHandler. Is this a feature of the behaviours added by WebServiceHost? Or is it because the message I'm building is simply wrong!? I can verify that the event log is indeed not receiving anything.
My current test environment is a WebGet method (both XML and Json) hosted in a service that is created with the WebServiceHostFactory, and Asp.Net compatibility switched off. The service method simply throws the exception in question.
try this:
Returning Error Details from AJAX-Enabled WCF Service
and this
http://zamd.net/2008/07/08/error-handling-with-webhttpbinding-for-ajaxjson/

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