简体   繁体   中英

CommunicationException using IErrorHandler in WCF

i'm using IErrorHandler to implement a global error handler for my WCF service. I've setup a dummy service that throws an exception to test, but I keep getting a CommunicationException instead of a FaultException (exception message is "The underlying connection was closed: The connection was closed unexpectedly."). Here's the relevant code:

IErrorHandler implementation:

    public bool HandleError(Exception error)
    {
        return true;
    }

    public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
    {
        if (!(error is FaultException))
        {
            MessageFault msgFault = null;

            FaultException<string> fex = new FaultException<string>("General Error");

            msgFault = fex.CreateMessageFault();

            fault = Message.CreateMessage(version, msgFault, string.Empty);
        }

    }

Any ideas?

Thanks, Gonzalo

Try this:

MessageFault msgFault = null;
FaultException<string> fex = new FaultException<string>("General Error");
msgFault = MessageFault.CreateFault(new FaultCode("Sender"), fex.Reason, fex, new NetDataContractSerializer());
fault = Message.CreateMessage(version, msgFault, string.Empty);

This works:

FaultException newEx = new FaultException();
MessageFault msgFault = newEx.CreateMessageFault();
fault = Message.CreateMessage(version, msgFault, newEx.Action);

Found here:

http://blogs.msdn.com/b/pedram/archive/2008/01/25/wcf-error-handling-and-some-best-practices.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM