I have a set of SOAP webservices that are wrapping exceptions using IErrorHandler, specifically:
public sealed class ErrorHandler : IErrorHandler
{
public bo
In a REST application I'm working on, I created a new class derived from WebFaultException
that attaches some additional data to caught service exceptions. Calling the CreatingMessageFault()
method on the instance of the derived class let me return my selected exception data from the ProvideFault()
method of the error handler as the SOAP fault, letting WCF determine the correct message format.
I am using webHttpBinding
to bind all but some third-party services.
Edit: Added code example
public class ErrorHandler : IErrorHandler, IServiceBehavior
{
public virtual void ProvideFault( Exception error, MessageVersion version, ref Message fault )
{
// Include next level of detail in message, if any.
MyFaultException myFaultException =
((error is MyFaultException) &&
((MyFaultException)error).Detail != null)
? new MyFaultException(error.Message + " - " +
((MyFaultException)error).Detail.Message, error)
: new MyFaultException( error.Message, error );
MessageFault messageFault = myFaultException.CreateMessageFault();
fault = Message.CreateMessage( version, messageFault, myFaultException.Action );
}
}
and
///
/// Class used to return exception data from my WCF services.
///
///
/// This class is used by a web service to pass exception data back and a
/// data object to the client. This class inherits WebFaultException, which
/// is handled specially by the WCF WebServiceHost2 service class and
/// generates a WebException on the client.
///
public class MyFaultException : WebFaultException
{
public class MyFaultException : WebFaultException
{
public MyFaultException(string message)
: this(HttpStatusCode.BadRequest, message) { }
public MyFaultException(HttpStatusCode statusCode, string message)
: base(new BusinessFault(message), statusCode) { }
}
then in your service, you can throw the exception to pass fault data to your client:
try
{
// Successful operation proceeds normally.
}
catch (ApplicationException e)
{
// Failure generates MyFaultException.
throw new MyFaultException("Operation failed with " + e.Message);
}