Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

wcf - Throwing generic FaultException

I have a WCF service that if something goes wrong throws a generic FaultException. I don't know why, sometimes the clients will catch a non-generic FaultException instead of the generic exception.

Does anybody know, what the problem is?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your service needs to handle all exceptions and wrap them into FaultException<T> where T is a data contract you have written. So the first step is to define a custom data contract that will contain your exception information:

[DataContract]
public class CustomFault
{
    public string Message { get; set; }
}

Then you instruct your service contract that its methods could potentially throw FaultException<CustomFault>. This allows the service to expose the CustomFault class in the wsdl, so that clients could generate a proxy class:

[ServiceContract]
public interface IMyServiceContract
{
    [FaultContract(typeof(CustomFault))]
    void MyMethod(string someArgument);
}

Next step is to implement this interface:

public class MyService : IMyServiceContract
{
    public void MyMethod(string someArgument)
    {
        // Do something here that could throw exceptions but don't catch yet
    }
}

To handle exceptions you could implement IErrorHandler which will be used whenever one of your service methods throws an exception. The purpose of this error handler is to wrap the exception into FaultException<CustomFault>:

public class MyErrorHandler : IErrorHandler
{
    public bool HandleError(Exception error)
    {
        return true;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message msg)
    {
        var customFault = new CustomFault()
        {
            Message = error.Message,
        };
        var fe = new FaultException<CustomFault>(customFault);
        MessageFault fault = fe.CreateMessageFault();
        string ns = "http://somenamespace/whatever";
        msg = Message.CreateMessage(version, fault, ns);
    }
}

Once you have registered your error handler, on the client side, you will always get FaultException<CustomFault>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...