SOAP Faults vs服务操作中的返回码

时间:2014-10-23 19:00:40

标签: wcf

假设我正在设计类似于此的服务接口:

[DataContract]
public class MakePaymentRequest
{    
    [DataMember]
    public string AccountID { get; set; }        

    [DataMember]
    public decimal PaymentAmount { get; set; }                
}

[DataContract]
public class MakePaymentResponse
{
    [DataMember]
    public string ConfirmationID { get; set; }

    [DataMember]
    public string ReceiptText { get; set; }        
}

[OperationContract]
MakePaymentResponse MakePayment(MakePaymentRequest makePaymentRequest);

有两种方法可以处理异常。

1)使用返回代码

将回复代码包含在回复中

    [DataMember]
    public string ReturnCode { get; set; }

以便" 000"的ReturnCode意味着成功等等。这种方法的缺点是我需要尝试 - 捕获操作方法:

public MakePaymentResponse MakePayment(MakePaymentRequest makePaymentRequest)
{
    try
    {
       // do stuff and return MakePaymentResponse with success code           
    }
    catch (Exception ex)
    {
       return new MakePaymentResponse { ReturnCode = "999" );
    } 
}

2)使用WCF全局异常处理并返回SOAP错误

将全局处理程序添加到自定义服务行为中:

public class FaultErrorHandler : IErrorHandler
{
   // ...
   public bool HandleError(Exception error)
    {
        try
        {
            _log.Error("Exception was caught", error);
        }
        catch { }
        return false;
    }

    public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
    {   
        if (fault == null)
        {
            FaultCode faultCode;
            if (error is ConfigurationErrorsException)
            { 
                faultCode = new FaultCode("Configuration");
            }
            else
            {
                faultCode = new FaultCode("Server error");
            }

            var fe = new FaultException<ReceiverFaultDetail>(new ReceiverFaultDetail("Unexpected error has occured", true), "Exception",  FaultCode.CreateReceiverFaultCode(faultCode));
            MessageFault mf = fe.CreateMessageFault();
            fault = Message.CreateMessage(version, mf, fe.Action);
        }            
    }
}

我的偏好是第二种情况,因为它更清洁,永远不会对频道造成错误,但我想了解是否有任何我错过了这条路线。

0 个答案:

没有答案