WCF/WebService: Interoperable exception handling

烈酒焚心 提交于 2019-12-04 03:33:43

There is no "automatic conversion". WCF will return a fault (I forget which one) when you have an unhandled exception. But since you didn't declare that fault, many, if not most, clients will fail if you return it.

You are meant to define your own faults and to return them instead. Consider:

[DataContract]
public class MySpecialFault
{
    public string MyMessage { get; set; }
}

[ServiceContract]
public interface IMyService
{
    [FaultContract(typeof (MySpecialFault))]
    [OperationContract]
    void MyOperation();
}

public class MyService : IMyService
{
    public void MyOperation()
    {
        try
        {
            // Do something interesting
        }
        catch (SomeExpectedException ex)
        {
            throw new FaultException<MySpecialFault>(
                new MySpecialFault {MyMessage = String.Format("Sorry, but {0}", ex.Message)});
        }
    }
}

Any client capable of handling faults will deal with this. The WSDL will define the fault, and they will see a fault with the Detail element containing a serialized version of the MySpecialFault instance that was sent. They'll be able to read all the properties of that instance.

Faults have been part of the SOAP specification since v1.1. They are explained in the SOAP Specification.

It is up to implementations (WCF, Java etc) to ensure that Faults are handled according to the specification.

Since WCF converts FaultExceptions to Faults according to the SOAP specification, FaultExceptions thrown from WCF are interoperable.

SOAP faults are interoperable but .Net exception classes are not good to be used in SOAP faults. Instead define your own DataContract class (e.g. AccessFault) and then use it in a FaultContract. see http://msdn.microsoft.com/en-us/library/ms733841.aspx

Whenever there is a UnauthorizedAccessException thrown at service boundary convert it to FaultException. This can be done in several ways like using Microsoft Enterprise Library Exception Handling Block or implementing the IErrorHandler interface.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!